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 806f2cad94..628f850c96 100644 --- a/.gitignore +++ b/.gitignore @@ -4,7 +4,7 @@ *.egg *.egg-info dist -build +/build/ eggs parts bin @@ -20,10 +20,13 @@ pip-log.txt # Unit test / coverage reports .coverage .tox +coverage.xml .DS_Store -docs/ +# sphinx build and rst folder +docs/build +docs/source/_rst # PyCharm/IntelliJ .idea @@ -34,4 +37,6 @@ docs/ # PyEnv .python-version -README.md.bak \ No newline at end of file +README.md.bak + +**/.openapi-generator* diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index c94b095c29..0000000000 --- a/.travis.yml +++ /dev/null @@ -1,13 +0,0 @@ -language: python -python: - - "2.7" - - "3.3" - - "3.4" - - "3.5" - - "3.6" -install: - - pip install virtualenv --upgrade - - make install - - make test-install -script: - - make test diff --git a/AUTHORS.md b/AUTHORS.md index a83624488c..58eabd023d 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -38,3 +38,4 @@ We'd like to thank the following people who have contributed to the - Evan Cooke - tysonholub - Brodan +- Kyle Jones \ No newline at end of file diff --git a/CHANGES.md b/CHANGES.md index 10e25597c8..37c7984d2f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -3,6 +3,3553 @@ 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** 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 index 255b19737d..41cb4474d0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -10,6 +10,8 @@ even better than it is today! Here are the guidelines we'd like you to follow: - [Documentation fixes](#docs) - [Submission Guidelines](#submit) - [Coding Rules](#rules) + - [Local Testing](#testing) + ## Code of Conduct @@ -20,8 +22,8 @@ it can be. ## Got an API/Product Question or Problem? If you have questions about how to use `twilio-python`, please see our -[docs][docs-link], and if you don't find the answer there, please contact -[help@twilio.com](mailto:help@twilio.com) with any issues you have. +[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? @@ -67,10 +69,6 @@ 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. -If you want to help improve the docs at -[https://www.twilio.com/docs/libraries/python][docs-link], please contact -[help@twilio.com](mailto:help@twilio.com). - ## Submission Guidelines ### Submitting an Issue @@ -104,7 +102,7 @@ Before you submit your pull request consider the following guidelines: * Make your changes in a new git branch: ```shell - git checkout -b my-fix-branch master + git checkout -b my-fix-branch main ``` * Create your patch, **including appropriate test cases**. @@ -131,7 +129,7 @@ Before you submit your pull request consider the following guidelines: git push origin my-fix-branch ``` -In GitHub, send a pull request to `twilio-python:master`. +In GitHub, send a pull request to `twilio-python:main`. If we suggest changes, then: * Make the required updates. @@ -154,6 +152,11 @@ you are working: * All features or bug fixes **must be tested** by one or more tests. * All classes and methods **must be documented**. -[docs-link]: https://www.twilio.com/docs/libraries/python +## 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 index b00b9be438..e6154b546b 100644 --- a/ISSUE_TEMPLATE.md +++ b/ISSUE_TEMPLATE.md @@ -1,9 +1,18 @@ -*Note: These issues are for bugs and feature requests for the helper libraries. -If you need help or support, please email help@twilio.com and one of our experts -will assist you!* + + +### 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 @@ -12,15 +21,10 @@ will assist you!* ### Exception/Log ``` - +# paste exception/log here ``` -### Steps to Reproduce -1. -2. -3. - +### Technical details: +* twilio-python version: +* python version: -### Feature Request -_If this is a feature request, make sure you search Issues for an existing -request before creating a new one!_ \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000..6485c1f845 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (C) 2023, Twilio, Inc. + +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 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/LICENSE.md b/LICENSE.md deleted file mode 100644 index b2d5d8b8f1..0000000000 --- a/LICENSE.md +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (C) 2018, Twilio, Inc. - -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 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. \ No newline at end of file diff --git a/MANIFEST.in b/MANIFEST.in index 43dd2a7cee..bc75be523a 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,2 +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 69dd2a8297..72cabbcfb1 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ -.PHONY: clean install analysis test test-install develop docs docs-install +.PHONY: clean install analysis test test-install test-docker develop docs docs-install prettier prettier-check venv: - @python --version || (echo "Python is not installed, please install Python 2 or Python 3"; exit 1); + @python --version || (echo "Python is not installed, Python 3.7+"; exit 1); virtualenv --python=python venv install: venv @@ -10,27 +10,37 @@ install: venv 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,W391,W291,W293,F401 tests - . venv/bin/activate; flake8 --ignore=E402,F401,W391,W291,W293 twilio --max-line-length=300 + . 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 - . venv/bin/activate; \ - find tests -type d | xargs nosetests +test: analysis prettier-check + . venv/bin/activate; pytest tests --ignore=tests/cluster -cover: +test-with-coverage: prettier-check . venv/bin/activate; \ - find tests -type d | xargs nosetests --with-coverage --cover-inclusive --cover-erase --cover-package=twilio + 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 pdoc + . venv/bin/activate; pip install -r tests/requirements.txt docs: - . venv/bin/activate; pdoc twilio --overwrite --html --html-dir 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 @@ -45,3 +55,24 @@ clean: 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} + +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 eada35aa9f..ed277788d1 100644 --- a/README.md +++ b/README.md @@ -1,73 +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"). +## Documentation -## Recent Update +The documentation for the Twilio API can be found [here][apidocs]. -As of release 6.5.0, Beta and Developer Preview products are now exposed via -the main `twilio-python` artifact. Releases of the `alpha` branch have been -discontinued. +The Python library documentation can be found [here][libdocs]. -If you were using the `alpha` release line, you should be able to switch back -to the normal release line without issue. +## Versions -If you were using the normal release line, you should now see several new -product lines that were historically hidden from you due to their Beta or -Developer Preview status. Such products are explicitly documented as -Beta/Developer Preview both in the Twilio docs and console, as well as through -in-line code documentation here in the library. +`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 +``` + +> **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" - python setup.py install +client = Client(account_sid, auth_token) -You may need to run the above commands with `sudo`. +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 +``` -### Migrate from 5.x -Please consult the [official migration guide](https://www.twilio.com/docs/libraries/python/migration-guide) for information on upgrading your application using twilio-python 5.x to 6.x +After a brief delay, you will receive the text message on your phone. -## Feedback -Report any feedback or problems with this Release Candidate to the [Github Issues](https://github.com/twilio/twilio-python/issues) for twilio-python. +> **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 +## 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. -Getting started with the Twilio API couldn't be easier. Create a -`Client` and you're ready to go. +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 `Twilio` 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 = "ACXXXXXXXXXXXXXXXXX" -token = "YYYYYYYYYYYYYYYYYY" -client = Client(account, token) +account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +auth_token = "your_auth_token" +client = Client(account_sid, auth_token) ``` -Alternately, a `Client` constructor without these parameters will +Authenticating with API Key and API Secret: + +```python +from twilio.rest import Client + +api_key = "XXXXXXXXXXXXXXXXX" +api_secret = "YYYYYYYYYYYYYYYYYY" +account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +client = Client(api_key, api_secret, account_sid) +``` + +Alternatively, a `Client` constructor without these parameters will look for `TWILIO_ACCOUNT_SID` and `TWILIO_AUTH_TOKEN` variables inside the current environment. @@ -75,20 +130,45 @@ 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 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 Client -account = "ACXXXXXXXXXXXXXXXXX" -token = "YYYYYYYYYYYYYYYYYY" -client = Client(account, token) +account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +auth_token = "your_auth_token" +client = Client(account_sid, auth_token) call = client.calls.create(to="9991231234", from_="9991231234", @@ -96,24 +176,121 @@ call = client.calls.create(to="9991231234", print(call.sid) ``` -### Send an SMS +### 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) +``` + +### 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 +client.messages.list(limit=20, page_size=20) +``` +This will make 1 call that will fetch 20 records from backend service. + +```python +client.messages.list(limit=20, page_size=10) +``` +This will make 2 calls that will fetch 10 records each from backend service. ```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. + +### Asynchronous API Requests + +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.http.async_http_client import AsyncTwilioHttpClient from twilio.rest import Client -account = "ACXXXXXXXXXXXXXXXXX" -token = "YYYYYYYYYYYYYYYYYY" -client = Client(account, token) +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!") -message = client.messages.create(to="+12316851234", from_="+15555555555", - body="Hello there!") +asyncio.run(main()) ``` -### Handling a call using TwiML +### Enable Debug Logging -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. +Log the API request and response data to the console: + +```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 @@ -127,3 +304,21 @@ print(str(r)) Welcome to twilio! ``` + +### 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 + +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. + +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! + +[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 index e3398eb735..03c196bf5b 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -1,17 +1,133 @@ # Upgrade Guide -_After `6.0.0` all `MINOR` and `MAJOR` version bumps will have upgrade notes +_`MAJOR` version bumps will have upgrade notes posted here._ -[2017-09-28] 6.6.x to 6.7.x ---------------------------- +## [2024-02-20] 8.x.x to 9.x.x +### Overview -### CHANGED - `Body` parameter on Chat `Message` creation is no longer required. +##### 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 @@ -20,6 +136,7 @@ client.chat.v2.services('IS123').channels('CH123').messages.create("this is the ``` #### 6.7.x + ```python from twilio.rest import Client diff --git a/VERSIONS.md b/VERSIONS.md index b1b648f4e2..0c2ae8d5b6 100644 --- a/VERSIONS.md +++ b/VERSIONS.md @@ -5,11 +5,11 @@ 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` +Semantic Versions take the form of `MAJOR.MINOR.PATCH` -When bugs are fixed in the library in a backwards compatible way, the `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. +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 @@ -19,8 +19,8 @@ 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 requires extensive reworking of code -will case the `MAJOR` version to be incremented by one, and the `MINOR` and +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 @@ -28,9 +28,8 @@ absolutely necessary. New `MAJOR` versions will be communicated in advance with ## Supported Versions -`twilio-python` follows an evergreen model of support. New features and -functionality will only be added to the current version. The current version - -1 will continue to be supported with bug fixes and security updates, but no new -features. +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]: http://semver.org/ \ No newline at end of file +[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/deploy.py b/deploy.py deleted file mode 100644 index 4649ede201..0000000000 --- a/deploy.py +++ /dev/null @@ -1,78 +0,0 @@ -from __future__ import print_function - -import os -import re -from argparse import ArgumentParser -from twilio import __version_info__, __version__ - -def main(version): - current_version = __version__ - - if version is None: - match = re.search(r'(\d+)$', __version_info__[-1]) - if not match or match.group() is None: - exit('Unable to auto bump version') - - patch = int(match.group()) - patch += 1 - - prefix = __version_info__[-1][:(-1 * len(match.group()))] - - new_patch = '{}{}'.format(prefix, patch) - - version = '.'.join(__version_info__[:-1] + (new_patch, )) - - print('Deploying {} -> {}'.format(current_version, version)) - - info = version.split('.') - - init_src = ("__version_info__ = ({version_info})\n" - "__version__ = '.'.join(__version_info__)\n") - init_src = init_src.format(version_info=', '.join(["'{}'".format(i) for i in info])) - - print('Updating twilio/__init__.py ... ', end="") - with open('twilio/__init__.py', 'w') as init_file: - init_file.write(init_src) - print('Done') - - new_readme = [] - - print('Updating README.md ... ', end="") - with open('README.md', 'r') as readme: - for line in readme.readlines(): - if current_version in line: - line = line.replace(current_version, version) - new_readme.append(line) - - with open('README.md', 'w') as readme: - readme.writelines(new_readme) - print('Done') - - print('git commit version bump') - os.system('git commit -am "Bumping version to {}"'.format(version)) - os.system('git push') - print('Done') - - print('Pushing to pypi') - os.system('make release') - print('Done') - - print('Adding git tag') - os.system('git tag {}'.format(version)) - os.system('git push --tags') - print('Done') - - # TODO: Remove this once 6.x is Generally Available - - print('!' * 80) - print('! {:^76} !'.format('Go hide latest RC and unhide latest 5.x')) - print('!' * 80) - - os.system('open "https://pypi.python.org/pypi?:action=pkg_edit&name=twilio"') - -if __name__ == '__main__': - parser = ArgumentParser() - parser.add_argument('version', nargs='?') - args = parser.parse_args() - - main(args.version) diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000000..017b358093 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,206 @@ +# -*- coding: utf-8 -*- +# +# Configuration file for the Sphinx documentation builder. +# +# 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 + + +# -- 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. +# +import os +import sys + +sys.path.insert(0, os.path.abspath("..")) +from twilio import __version__ + + +# -- Project information ----------------------------------------------------- + +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__ + + +# -- General configuration --------------------------------------------------- + +# 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", + "sphinx.ext.doctest", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.ifconfig", + "sphinx.ext.viewcode", + "recommonmark", +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["source/_templates"] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +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. +# +# 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. +# 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" + + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +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 = {} + +html_static_path = ["source/_static"] + +# 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", + ] +} + + +# -- Options for HTMLHelp output --------------------------------------------- + +# Output file base name for HTML help builder. +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, or own class]). +latex_documents = [ + ( + master_doc, + "twilio-python.tex", + "twilio-python Documentation", + "Twilio", + "manual", + ), +] + + +# -- Options for manual page output ------------------------------------------ + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +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 ------------------------------------------------- + +# Bibliographic Dublin Core info. +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 = '' + +# A unique identification for the text. +# +# epub_uid = '' + +# A list of files that should not be packed into the epub file. +epub_exclude_files = ["search.html"] + + +# -- Extension configuration ------------------------------------------------- + +# -- Options for intersphinx extension --------------------------------------- + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = {"python": ("https://docs.python.org/3", None)} 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/examples/basic_usage.py b/examples/basic_usage.py index 4a956fae90..a1ad25b0f2 100644 --- a/examples/basic_usage.py +++ b/examples/basic_usage.py @@ -3,8 +3,8 @@ 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') +ACCOUNT_SID = os.environ.get("TWILIO_ACCOUNT_SID") +AUTH_TOKEN = os.environ.get("TWILIO_AUTH_TOKEN") def example(): @@ -15,31 +15,31 @@ def example(): # Get all messages all_messages = client.messages.list() - print('There are {} messages in your account.'.format(len(all_messages))) + 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:') + 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("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("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("Making a call...") + new_call = client.calls.create(to="XXXX", from_="YYYY", method="GET") - print('Serving TwiML') + print("Serving TwiML") twiml_response = VoiceResponse() - twiml_response.say('Hello!') + twiml_response.say("Hello!") twiml_response.hangup() twiml_xml = twiml_response.to_xml() - print('Generated twiml: {}'.format(twiml_xml)) + print("Generated twiml: {}".format(twiml_xml)) -if __name__ == '__main__': +if __name__ == "__main__": example() diff --git a/examples/client_validation.py b/examples/client_validation.py index e4fbf67cc9..a7bc08e81a 100644 --- a/examples/client_validation.py +++ b/examples/client_validation.py @@ -6,15 +6,16 @@ Encoding, PublicFormat, PrivateFormat, - NoEncryption + 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') +ACCOUNT_SID = os.environ.get("TWILIO_ACCOUNT_SID") +AUTH_TOKEN = os.environ.get("TWILIO_AUTH_TOKEN") + def example(): """ @@ -28,45 +29,45 @@ def example(): # 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') + print("Creating new api key...") + api_key = client.new_keys.create(friendly_name="ClientValidationApiKey") # Generate a new RSA Keypair - print('Generating RSA key pair...') + print("Generating RSA key pair...") key_pair = rsa.generate_private_key( - public_exponent=65537, - key_size=2048, - backend=default_backend() + 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() ) - 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...') + print("Registering public key with Twilio...") credential = client.accounts.credentials.public_key.create( - public_key, - friendly_name='ClientValidationPublicKey' + 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 + 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) + client = Client( + api_key.sid, api_key.secret, ACCOUNT_SID, http_client=validation_client + ) # Use the library as usual - print('Trying out client validation...') + print("Trying out client validation...") messages = client.messages.list(limit=10) for m in messages: - print('Message {}'.format(m.sid)) + print("Message {}".format(m.sid)) - print('Client validation works!') + print("Client validation works!") -if __name__ == '__main__': +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 ebd08acafa..7bc9e41806 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,8 +1,8 @@ -flake8 -mock -nose -six -requests>=2.0.0 -socksipy-branch -PyJWT==1.4.2 -twine +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 index 5bde4372f5..4c18756789 100644 --- a/setup.cfg +++ b/setup.cfg @@ -2,7 +2,12 @@ universal = 1 [metadata] -description-file = README.md +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 85a3d78758..97004e4a02 --- a/setup.py +++ b/setup.py @@ -1,10 +1,7 @@ -from __future__ import with_statement -import sys from setuptools import setup, find_packages -__version__ = None -with open('twilio/__init__.py') as f: - exec(f.read()) +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: @@ -15,51 +12,39 @@ # documentation: http://pypi.python.org/pypi/setuptools setup( - name = "twilio", - version = __version__, - description = "Twilio API client and TwiML generator", - author = "Twilio", - author_email = "help@twilio.com", - url = "https://github.com/twilio/twilio-python/", - keywords = ["twilio","twiml"], - install_requires = [ - "six", - "pytz", - "PyJWT >= 1.4.2", + 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", ], - extras_require={ - ':python_version<"3.0"': [ - "requests[security] >= 2.0.0", - ], - ':python_version>="3.0"': [ - "requests >= 2.0.0", - "pysocks", - ], - }, - packages = find_packages(exclude=['tests', 'tests.*']), + packages=find_packages(exclude=["tests", "tests.*"]), include_package_data=True, - classifiers = [ + 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.7", - "Programming Language :: Python :: 3.3", - "Programming Language :: Python :: 3.4", - "Programming Language :: Python :: 3.5", - "Programming Language :: Python :: 3.6", + "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 making calls using the Twilio REST API. - The Twilio REST API lets to you initiate outgoing calls, list previous calls, - and much more. See https://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/__init__.py b/tests/__init__.py index 8afbc82772..8a15535503 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -7,9 +7,11 @@ class IntegrationTestCase(unittest.TestCase): def setUp(self): super(IntegrationTestCase, self).setUp() - self.account_sid = 'AC' + 'a' * 32 - self.auth_token = 'AUTHTOKEN' + 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) + 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 index 066125b89c..8f71514314 100644 --- a/tests/holodeck.py +++ b/tests/holodeck.py @@ -1,17 +1,17 @@ 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 = [] @@ -24,30 +24,53 @@ def mock(self, response, request=None): 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: + if req == request or req == self.add_standard_headers(request): return - message = '\nHolodeck never received a request matching: \n + {}\n'.format(request) + 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) + message += "Requests received:\n" + message += "\n".join(" * {}".format(r) for r in self.requests) else: - message += 'No Requests received' + 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): - + 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) @@ -56,12 +79,11 @@ def request(self, if hologram.request == request: return hologram.response - message = '\nHolodeck has no hologram for: {}\n'.format(request) + 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) + message += "Holograms loaded:\n" + message += "\n".join(" - {}".format(h.request) for h in self._holograms) else: - message += 'No Holograms loaded' + message += "No Holograms loaded" raise TwilioRestException(404, url, message, method=method) - diff --git a/tests/integration/__init__.py b/tests/integration/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/accounts/__init__.py b/tests/integration/accounts/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/accounts/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/accounts/v1/__init__.py b/tests/integration/accounts/v1/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/accounts/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/accounts/v1/credential/__init__.py b/tests/integration/accounts/v1/credential/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/accounts/v1/credential/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/accounts/v1/credential/test_aws.py b/tests/integration/accounts/v1/credential/test_aws.py deleted file mode 100644 index a4f545e9dd..0000000000 --- a/tests/integration/accounts/v1/credential/test_aws.py +++ /dev/null @@ -1,206 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class AwsTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.accounts.v1.credentials \ - .aws.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://accounts.twilio.com/v1/Credentials/AWS', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "credentials": [], - "meta": { - "first_page_url": "https://accounts.twilio.com/v1/Credentials/AWS?PageSize=50&Page=0", - "key": "credentials", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://accounts.twilio.com/v1/Credentials/AWS?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.accounts.v1.credentials \ - .aws.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "credentials": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-31T04:00:00Z", - "date_updated": "2015-07-31T04:00:00Z", - "friendly_name": "friendly_name", - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://accounts.twilio.com/v1/Credentials/AWS/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://accounts.twilio.com/v1/Credentials/AWS?PageSize=50&Page=0", - "key": "credentials", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://accounts.twilio.com/v1/Credentials/AWS?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.accounts.v1.credentials \ - .aws.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.accounts.v1.credentials \ - .aws.create(credentials="AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY") - - values = {'Credentials': "AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://accounts.twilio.com/v1/Credentials/AWS', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-31T04:00:00Z", - "date_updated": "2015-07-31T04:00:00Z", - "friendly_name": "friendly_name", - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://accounts.twilio.com/v1/Credentials/AWS/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.accounts.v1.credentials \ - .aws.create(credentials="AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY") - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.accounts.v1.credentials \ - .aws(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://accounts.twilio.com/v1/Credentials/AWS/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-31T04:00:00Z", - "date_updated": "2015-07-31T04:00:00Z", - "friendly_name": "friendly_name", - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://accounts.twilio.com/v1/Credentials/AWS/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.accounts.v1.credentials \ - .aws(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.accounts.v1.credentials \ - .aws(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://accounts.twilio.com/v1/Credentials/AWS/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-31T04:00:00Z", - "date_updated": "2015-07-31T04:00:00Z", - "friendly_name": "friendly_name", - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://accounts.twilio.com/v1/Credentials/AWS/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.accounts.v1.credentials \ - .aws(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.accounts.v1.credentials \ - .aws(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://accounts.twilio.com/v1/Credentials/AWS/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.accounts.v1.credentials \ - .aws(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/accounts/v1/credential/test_public_key.py b/tests/integration/accounts/v1/credential/test_public_key.py deleted file mode 100644 index 1977658221..0000000000 --- a/tests/integration/accounts/v1/credential/test_public_key.py +++ /dev/null @@ -1,206 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class PublicKeyTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.accounts.v1.credentials \ - .public_key.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://accounts.twilio.com/v1/Credentials/PublicKeys', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "credentials": [], - "meta": { - "first_page_url": "https://accounts.twilio.com/v1/Credentials/PublicKeys?PageSize=50&Page=0", - "key": "credentials", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://accounts.twilio.com/v1/Credentials/PublicKeys?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.accounts.v1.credentials \ - .public_key.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "credentials": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-31T04:00:00Z", - "date_updated": "2015-07-31T04:00:00Z", - "friendly_name": "friendly_name", - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://accounts.twilio.com/v1/Credentials/PublicKeys/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://accounts.twilio.com/v1/Credentials/PublicKeys?PageSize=50&Page=0", - "key": "credentials", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://accounts.twilio.com/v1/Credentials/PublicKeys?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.accounts.v1.credentials \ - .public_key.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.accounts.v1.credentials \ - .public_key.create(public_key="publickey") - - values = {'PublicKey': "publickey", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://accounts.twilio.com/v1/Credentials/PublicKeys', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-31T04:00:00Z", - "date_updated": "2015-07-31T04:00:00Z", - "friendly_name": "friendly_name", - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://accounts.twilio.com/v1/Credentials/PublicKeys/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.accounts.v1.credentials \ - .public_key.create(public_key="publickey") - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.accounts.v1.credentials \ - .public_key(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://accounts.twilio.com/v1/Credentials/PublicKeys/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-31T04:00:00Z", - "date_updated": "2015-07-31T04:00:00Z", - "friendly_name": "friendly_name", - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://accounts.twilio.com/v1/Credentials/PublicKeys/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.accounts.v1.credentials \ - .public_key(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.accounts.v1.credentials \ - .public_key(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://accounts.twilio.com/v1/Credentials/PublicKeys/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-31T04:00:00Z", - "date_updated": "2015-07-31T04:00:00Z", - "friendly_name": "friendly_name", - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://accounts.twilio.com/v1/Credentials/PublicKeys/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.accounts.v1.credentials \ - .public_key(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.accounts.v1.credentials \ - .public_key(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://accounts.twilio.com/v1/Credentials/PublicKeys/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.accounts.v1.credentials \ - .public_key(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/accounts/v1/test_credential.py b/tests/integration/accounts/v1/test_credential.py deleted file mode 100644 index b04a4cbfef..0000000000 --- a/tests/integration/accounts/v1/test_credential.py +++ /dev/null @@ -1,16 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class CredentialTestCase(IntegrationTestCase): - pass diff --git a/tests/integration/api/__init__.py b/tests/integration/api/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/api/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/api/v2010/__init__.py b/tests/integration/api/v2010/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/api/v2010/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/api/v2010/account/__init__.py b/tests/integration/api/v2010/account/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/api/v2010/account/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/api/v2010/account/address/__init__.py b/tests/integration/api/v2010/account/address/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/api/v2010/account/address/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/api/v2010/account/address/test_dependent_phone_number.py b/tests/integration/api/v2010/account/address/test_dependent_phone_number.py deleted file mode 100644 index 617c12081a..0000000000 --- a/tests/integration/api/v2010/account/address/test_dependent_phone_number.py +++ /dev/null @@ -1,105 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class DependentPhoneNumberTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .addresses(sid="ADXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .dependent_phone_numbers.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Addresses/ADXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/DependentPhoneNumbers.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "dependent_phone_numbers": [ - { - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "3197004499318", - "phone_number": "+3197004499318", - "voice_url": null, - "voice_method": "POST", - "voice_fallback_url": null, - "voice_fallback_method": "POST", - "voice_caller_id_lookup": false, - "date_created": "Thu, 23 Feb 2017 10:26:31 -0800", - "date_updated": "Thu, 23 Feb 2017 10:26:31 -0800", - "sms_url": "", - "sms_method": "POST", - "sms_fallback_url": "", - "sms_fallback_method": "POST", - "address_requirements": "any", - "capabilities": { - "Voice": false, - "SMS": true, - "MMS": false - }, - "status_callback": "", - "status_callback_method": "POST", - "api_version": "2010-04-01", - "voice_application_sid": null, - "sms_application_sid": "", - "trunk_sid": null, - "emergency_status": "Inactive", - "emergency_address_sid": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Addresses/ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DependentPhoneNumbers.json?Page=0&PageSize=50", - "next_page_uri": null, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Addresses/ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DependentPhoneNumbers.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .addresses(sid="ADXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .dependent_phone_numbers.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "dependent_phone_numbers": [], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Addresses/ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DependentPhoneNumbers.json?Page=0&PageSize=50", - "next_page_uri": null, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Addresses/ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DependentPhoneNumbers.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .addresses(sid="ADXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .dependent_phone_numbers.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/available_phone_number/__init__.py b/tests/integration/api/v2010/account/available_phone_number/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/api/v2010/account/available_phone_number/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/api/v2010/account/available_phone_number/test_local.py b/tests/integration/api/v2010/account/available_phone_number/test_local.py deleted file mode 100644 index d721751a8c..0000000000 --- a/tests/integration/api/v2010/account/available_phone_number/test_local.py +++ /dev/null @@ -1,101 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class LocalTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers(country_code="US") \ - .local.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AvailablePhoneNumbers/US/Local.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "available_phone_numbers": [ - { - "address_requirements": "none", - "beta": false, - "capabilities": { - "mms": true, - "sms": false, - "voice": true - }, - "friendly_name": "(808) 925-1571", - "iso_country": "US", - "lata": "834", - "latitude": "19.720000", - "locality": "Hilo", - "longitude": "-155.090000", - "phone_number": "+18089251571", - "postal_code": "96720", - "rate_center": "HILO", - "region": "HI" - } - ], - "end": 1, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/Local.json?PageSize=50&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/Local.json?PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/Local.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers(country_code="US") \ - .local.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "available_phone_numbers": [], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/Local.json?PageSize=50&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/Local.json?PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/Local.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers(country_code="US") \ - .local.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/available_phone_number/test_machine_to_machine.py b/tests/integration/api/v2010/account/available_phone_number/test_machine_to_machine.py deleted file mode 100644 index 24895864bb..0000000000 --- a/tests/integration/api/v2010/account/available_phone_number/test_machine_to_machine.py +++ /dev/null @@ -1,101 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class MachineToMachineTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers(country_code="US") \ - .machine_to_machine.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AvailablePhoneNumbers/US/MachineToMachine.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "available_phone_numbers": [ - { - "address_requirements": "none", - "beta": false, - "capabilities": { - "mms": false, - "sms": true, - "voice": false - }, - "friendly_name": "+4759440374", - "iso_country": "NO", - "lata": null, - "latitude": null, - "locality": null, - "longitude": null, - "phone_number": "+4759440374", - "postal_code": null, - "rate_center": null, - "region": null - } - ], - "end": 1, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/MachineToMachine.json?PageSize=50&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/MachineToMachine.json?PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/MachineToMachine.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers(country_code="US") \ - .machine_to_machine.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "available_phone_numbers": [], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/MachineToMachine.json?PageSize=50&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/MachineToMachine.json?PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/MachineToMachine.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers(country_code="US") \ - .machine_to_machine.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/available_phone_number/test_mobile.py b/tests/integration/api/v2010/account/available_phone_number/test_mobile.py deleted file mode 100644 index 6d13d13b9a..0000000000 --- a/tests/integration/api/v2010/account/available_phone_number/test_mobile.py +++ /dev/null @@ -1,100 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class MobileTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers(country_code="US") \ - .mobile.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AvailablePhoneNumbers/US/Mobile.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "available_phone_numbers": [ - { - "address_requirements": "none", - "beta": false, - "capabilities": { - "mms": false, - "sms": true, - "voice": false - }, - "friendly_name": "+4759440374", - "iso_country": "NO", - "lata": null, - "latitude": null, - "locality": null, - "longitude": null, - "phone_number": "+4759440374", - "postal_code": null, - "rate_center": null, - "region": null - } - ], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/Mobile.json?PageSize=50&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/Mobile.json?PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/Mobile.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers(country_code="US") \ - .mobile.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "available_phone_numbers": [], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/Mobile.json?PageSize=50&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/Mobile.json?PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/Mobile.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers(country_code="US") \ - .mobile.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/available_phone_number/test_national.py b/tests/integration/api/v2010/account/available_phone_number/test_national.py deleted file mode 100644 index f8eec4b933..0000000000 --- a/tests/integration/api/v2010/account/available_phone_number/test_national.py +++ /dev/null @@ -1,101 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class NationalTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers(country_code="US") \ - .national.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AvailablePhoneNumbers/US/National.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "available_phone_numbers": [ - { - "address_requirements": "none", - "beta": false, - "capabilities": { - "mms": false, - "sms": true, - "voice": false - }, - "friendly_name": "+4759440374", - "iso_country": "NO", - "lata": null, - "latitude": null, - "locality": null, - "longitude": null, - "phone_number": "+4759440374", - "postal_code": null, - "rate_center": null, - "region": null - } - ], - "end": 1, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/National.json?PageSize=50&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/National.json?PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/National.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers(country_code="US") \ - .national.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "available_phone_numbers": [], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/National.json?PageSize=50&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/National.json?PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/National.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers(country_code="US") \ - .national.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/available_phone_number/test_shared_cost.py b/tests/integration/api/v2010/account/available_phone_number/test_shared_cost.py deleted file mode 100644 index 9d133a6f20..0000000000 --- a/tests/integration/api/v2010/account/available_phone_number/test_shared_cost.py +++ /dev/null @@ -1,101 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class SharedCostTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers(country_code="US") \ - .shared_cost.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AvailablePhoneNumbers/US/SharedCost.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "available_phone_numbers": [ - { - "address_requirements": "none", - "beta": false, - "capabilities": { - "mms": false, - "sms": true, - "voice": false - }, - "friendly_name": "+4759440374", - "iso_country": "NO", - "lata": null, - "latitude": null, - "locality": null, - "longitude": null, - "phone_number": "+4759440374", - "postal_code": null, - "rate_center": null, - "region": null - } - ], - "end": 1, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/SharedCost.json?PageSize=50&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/SharedCost.json?PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/SharedCost.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers(country_code="US") \ - .shared_cost.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "available_phone_numbers": [], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/SharedCost.json?PageSize=50&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/SharedCost.json?PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/SharedCost.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers(country_code="US") \ - .shared_cost.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/available_phone_number/test_toll_free.py b/tests/integration/api/v2010/account/available_phone_number/test_toll_free.py deleted file mode 100644 index 274fa3c58d..0000000000 --- a/tests/integration/api/v2010/account/available_phone_number/test_toll_free.py +++ /dev/null @@ -1,100 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class TollFreeTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers(country_code="US") \ - .toll_free.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AvailablePhoneNumbers/US/TollFree.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "available_phone_numbers": [ - { - "address_requirements": "none", - "beta": false, - "capabilities": { - "mms": true, - "sms": true, - "voice": true - }, - "friendly_name": "(800) 100-0052", - "iso_country": "US", - "lata": null, - "latitude": null, - "locality": null, - "longitude": null, - "phone_number": "+18001000052", - "postal_code": null, - "rate_center": null, - "region": null - } - ], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/TollFree.json?PageSize=50&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/TollFree.json?PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/TollFree.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers(country_code="US") \ - .toll_free.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "available_phone_numbers": [], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/TollFree.json?PageSize=50&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/TollFree.json?PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/TollFree.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers(country_code="US") \ - .toll_free.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/available_phone_number/test_voip.py b/tests/integration/api/v2010/account/available_phone_number/test_voip.py deleted file mode 100644 index 6341d4b635..0000000000 --- a/tests/integration/api/v2010/account/available_phone_number/test_voip.py +++ /dev/null @@ -1,101 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class VoipTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers(country_code="US") \ - .voip.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AvailablePhoneNumbers/US/Voip.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "available_phone_numbers": [ - { - "address_requirements": "none", - "beta": false, - "capabilities": { - "mms": false, - "sms": true, - "voice": false - }, - "friendly_name": "+4759440374", - "iso_country": "NO", - "lata": null, - "latitude": null, - "locality": null, - "longitude": null, - "phone_number": "+4759440374", - "postal_code": null, - "rate_center": null, - "region": null - } - ], - "end": 1, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/Voip.json?PageSize=50&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/Voip.json?PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/Voip.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers(country_code="US") \ - .voip.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "available_phone_numbers": [], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/Voip.json?PageSize=50&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/Voip.json?PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/Voip.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers(country_code="US") \ - .voip.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/call/__init__.py b/tests/integration/api/v2010/account/call/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/api/v2010/account/call/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/api/v2010/account/call/test_feedback.py b/tests/integration/api/v2010/account/call/test_feedback.py deleted file mode 100644 index 8767d4ce91..0000000000 --- a/tests/integration/api/v2010/account/call/test_feedback.py +++ /dev/null @@ -1,132 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class FeedbackTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .feedback().create(quality_score=1) - - values = {'QualityScore': 1, } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Feedback.json', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Thu, 20 Aug 2015 21:45:46 +0000", - "date_updated": "Thu, 20 Aug 2015 21:45:46 +0000", - "issues": [ - "imperfect-audio", - "post-dial-delay" - ], - "quality_score": 5, - "sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .feedback().create(quality_score=1) - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .feedback().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Feedback.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Thu, 20 Aug 2015 21:45:46 +0000", - "date_updated": "Thu, 20 Aug 2015 21:45:46 +0000", - "issues": [ - "imperfect-audio", - "post-dial-delay" - ], - "quality_score": 5, - "sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .feedback().fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .feedback().update(quality_score=1) - - values = {'QualityScore': 1, } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Feedback.json', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Thu, 20 Aug 2015 21:45:46 +0000", - "date_updated": "Thu, 20 Aug 2015 21:45:46 +0000", - "issues": [ - "imperfect-audio", - "post-dial-delay" - ], - "quality_score": 5, - "sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .feedback().update(quality_score=1) - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/call/test_feedback_summary.py b/tests/integration/api/v2010/account/call/test_feedback_summary.py deleted file mode 100644 index 2c7dc68ee6..0000000000 --- a/tests/integration/api/v2010/account/call/test_feedback_summary.py +++ /dev/null @@ -1,144 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from datetime import date -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base import serialize -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class FeedbackSummaryTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls \ - .feedback_summaries.create(start_date=date(2008, 1, 2), end_date=date(2008, 1, 2)) - - values = { - 'StartDate': serialize.iso8601_date(date(2008, 1, 2)), - 'EndDate': serialize.iso8601_date(date(2008, 1, 2)), - } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/FeedbackSummary.json', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_count": 10200, - "call_feedback_count": 729, - "end_date": "2011-01-01", - "include_subaccounts": false, - "issues": [ - { - "count": 45, - "description": "imperfect-audio", - "percentage_of_total_calls": "0.04%" - } - ], - "quality_score_average": 4.5, - "quality_score_median": 4, - "quality_score_standard_deviation": 1, - "sid": "FSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "start_date": "2011-01-01", - "status": "completed", - "date_created": "Tue, 31 Aug 2010 20:36:28 +0000", - "date_updated": "Tue, 31 Aug 2010 20:36:44 +0000" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls \ - .feedback_summaries.create(start_date=date(2008, 1, 2), end_date=date(2008, 1, 2)) - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls \ - .feedback_summaries(sid="FSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/FeedbackSummary/FSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_count": 10200, - "call_feedback_count": 729, - "end_date": "2011-01-01", - "include_subaccounts": false, - "issues": [ - { - "count": 45, - "description": "imperfect-audio", - "percentage_of_total_calls": "0.04%" - } - ], - "quality_score_average": 4.5, - "quality_score_median": 4, - "quality_score_standard_deviation": 1, - "sid": "FSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "start_date": "2011-01-01", - "status": "completed", - "date_created": "Tue, 31 Aug 2010 20:36:28 +0000", - "date_updated": "Tue, 31 Aug 2010 20:36:44 +0000" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls \ - .feedback_summaries(sid="FSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls \ - .feedback_summaries(sid="FSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/FeedbackSummary/FSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls \ - .feedback_summaries(sid="FSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/api/v2010/account/call/test_notification.py b/tests/integration/api/v2010/account/call/test_notification.py deleted file mode 100644 index bb56c8039c..0000000000 --- a/tests/integration/api/v2010/account/call/test_notification.py +++ /dev/null @@ -1,169 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class NotificationTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .notifications(sid="NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Notifications/NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2008-08-01", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Tue, 18 Aug 2015 08:46:56 +0000", - "date_updated": "Tue, 18 Aug 2015 08:46:57 +0000", - "error_code": "15003", - "log": "1", - "message_date": "Tue, 18 Aug 2015 08:46:56 +0000", - "message_text": "statusCallback=http%3A%2F%2Fexample.com%2Ffoo.xml&ErrorCode=15003&LogLevel=WARN&Msg=Got+HTTP+404+response+to+http%3A%2F%2Fexample.com%2Ffoo.xml", - "more_info": "https://www.twilio.com/docs/errors/15003", - "request_method": null, - "request_url": "", - "request_variables": "", - "response_body": "", - "response_headers": "", - "sid": "NOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications/NOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .notifications(sid="NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .notifications(sid="NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Notifications/NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .notifications(sid="NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .notifications.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Notifications.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json?PageSize=50&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json?PageSize=50&Page=0", - "next_page_uri": null, - "notifications": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2008-08-01", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Tue, 18 Aug 2015 08:46:56 +0000", - "date_updated": "Tue, 18 Aug 2015 08:46:57 +0000", - "error_code": "15003", - "log": "1", - "message_date": "Tue, 18 Aug 2015 08:46:56 +0000", - "message_text": "statusCallback=http%3A%2F%2Fexample.com%2Ffoo.xml&ErrorCode=15003&LogLevel=WARN&Msg=Got+HTTP+404+response+to+http%3A%2F%2Fexample.com%2Ffoo.xml", - "more_info": "https://www.twilio.com/docs/errors/15003", - "request_method": null, - "request_url": "", - "sid": "NOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications/NOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .notifications.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json?PageSize=50&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json?PageSize=50&Page=0", - "next_page_uri": null, - "notifications": [], - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .notifications.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/call/test_recording.py b/tests/integration/api/v2010/account/call/test_recording.py deleted file mode 100644 index e264c4e282..0000000000 --- a/tests/integration/api/v2010/account/call/test_recording.py +++ /dev/null @@ -1,176 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class RecordingTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings/REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conference_sid": null, - "channels": 2, - "date_created": "Fri, 14 Oct 2016 21:56:34 +0000", - "date_updated": "Fri, 14 Oct 2016 21:56:38 +0000", - "start_time": "Fri, 14 Oct 2016 21:56:34 +0000", - "end_time": "Fri, 14 Oct 2016 21:56:38 +0000", - "price": "-0.0025", - "price_unit": "USD", - "duration": "4", - "sid": "REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "encryption_details": { - "encryption_public_key_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "encryption_cek": "OV4h6zrsxMIW7h0Zfqwfn6TI2GCNl54KALlg8wn8YB8KYZhXt6HlgvBWAmQTlfYVeLWydMiCewY0YkDDT1xmNe5huEo9vjuKBS5OmYK4CZkSx1NVv3XOGrZHpd2Pl/5WJHVhUK//AUO87uh5qnUP2E0KoLh1nyCLeGcEkXU0RfpPn/6nxjof/n6m6OzZOyeIRK4Oed5+rEtjqFDfqT0EVKjs6JAxv+f0DCc1xYRHl2yV8bahUPVKs+bHYdy4PVszFKa76M/Uae4jFA9Lv233JqWcxj+K2UoghuGhAFbV/JQIIswY2CBYI8JlVSifSqNEl9vvsTJ8bkVMm3MKbG2P7Q==", - "encryption_iv": "8I2hhNIYNTrwxfHk" - }, - "source": "StartCallRecordingAPI", - "status": "completed", - "error_code": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings/REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json?PageSize=50&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "recordings": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conference_sid": null, - "channels": 2, - "date_created": "Fri, 14 Oct 2016 21:56:34 +0000", - "date_updated": "Fri, 14 Oct 2016 21:56:38 +0000", - "start_time": "Fri, 14 Oct 2016 21:56:34 +0000", - "end_time": "Fri, 14 Oct 2016 21:56:38 +0000", - "price": "-0.0025", - "price_unit": "USD", - "duration": "4", - "sid": "REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "encryption_details": { - "encryption_public_key_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "encryption_cek": "OV4h6zrsxMIW7h0Zfqwfn6TI2GCNl54KALlg8wn8YB8KYZhXt6HlgvBWAmQTlfYVeLWydMiCewY0YkDDT1xmNe5huEo9vjuKBS5OmYK4CZkSx1NVv3XOGrZHpd2Pl/5WJHVhUK//AUO87uh5qnUP2E0KoLh1nyCLeGcEkXU0RfpPn/6nxjof/n6m6OzZOyeIRK4Oed5+rEtjqFDfqT0EVKjs6JAxv+f0DCc1xYRHl2yV8bahUPVKs+bHYdy4PVszFKa76M/Uae4jFA9Lv233JqWcxj+K2UoghuGhAFbV/JQIIswY2CBYI8JlVSifSqNEl9vvsTJ8bkVMm3MKbG2P7Q==", - "encryption_iv": "8I2hhNIYNTrwxfHk" - }, - "source": "StartCallRecordingAPI", - "status": "completed", - "error_code": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json?PageSize=50&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "recordings": [], - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/conference/__init__.py b/tests/integration/api/v2010/account/conference/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/api/v2010/account/conference/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/api/v2010/account/conference/test_participant.py b/tests/integration/api/v2010/account/conference/test_participant.py deleted file mode 100644 index 647e0f2174..0000000000 --- a/tests/integration/api/v2010/account/conference/test_participant.py +++ /dev/null @@ -1,261 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ParticipantTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences(sid="CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(call_sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Conferences/CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conference_sid": "CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Fri, 18 Feb 2011 21:07:19 +0000", - "date_updated": "Fri, 18 Feb 2011 21:07:19 +0000", - "end_conference_on_exit": false, - "muted": false, - "hold": false, - "status": "complete", - "start_conference_on_enter": true, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences(sid="CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(call_sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences(sid="CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(call_sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Conferences/CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conference_sid": "CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Fri, 18 Feb 2011 21:07:19 +0000", - "date_updated": "Fri, 18 Feb 2011 21:07:19 +0000", - "end_conference_on_exit": false, - "muted": false, - "hold": false, - "status": "complete", - "start_conference_on_enter": true, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences(sid="CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(call_sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences(sid="CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.create(from_="+15017122661", to="+15558675310") - - values = {'From': "+15017122661", 'To': "+15558675310", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Conferences/CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants.json', - data=values, - )) - - def test_create_with_sid_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conference_sid": "CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Fri, 18 Feb 2011 21:07:19 +0000", - "date_updated": "Fri, 18 Feb 2011 21:07:19 +0000", - "end_conference_on_exit": false, - "muted": false, - "hold": false, - "status": "complete", - "start_conference_on_enter": true, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences(sid="CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.create(from_="+15017122661", to="+15558675310") - - self.assertIsNotNone(actual) - - def test_create_with_friendly_name_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conference_sid": "CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Fri, 18 Feb 2011 21:07:19 +0000", - "date_updated": "Fri, 18 Feb 2011 21:07:19 +0000", - "end_conference_on_exit": false, - "muted": false, - "hold": false, - "status": "complete", - "start_conference_on_enter": true, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences(sid="CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.create(from_="+15017122661", to="+15558675310") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences(sid="CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(call_sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Conferences/CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences(sid="CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(call_sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences(sid="CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Conferences/CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants.json?Page=0&PageSize=50", - "next_page_uri": null, - "page": 0, - "page_size": 50, - "participants": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conference_sid": "CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Fri, 18 Feb 2011 21:07:19 +0000", - "date_updated": "Fri, 18 Feb 2011 21:07:19 +0000", - "end_conference_on_exit": false, - "muted": false, - "hold": false, - "status": "complete", - "start_conference_on_enter": true, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "previous_page_uri": null, - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences(sid="CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants.json?Page=0&PageSize=50", - "next_page_uri": null, - "page": 0, - "page_size": 50, - "participants": [], - "previous_page_uri": null, - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences(sid="CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/incoming_phone_number/__init__.py b/tests/integration/api/v2010/account/incoming_phone_number/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/api/v2010/account/incoming_phone_number/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/api/v2010/account/incoming_phone_number/assigned_add_on/__init__.py b/tests/integration/api/v2010/account/incoming_phone_number/assigned_add_on/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/api/v2010/account/incoming_phone_number/assigned_add_on/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/api/v2010/account/incoming_phone_number/assigned_add_on/test_assigned_add_on_extension.py b/tests/integration/api/v2010/account/incoming_phone_number/assigned_add_on/test_assigned_add_on_extension.py deleted file mode 100644 index 3f57893127..0000000000 --- a/tests/integration/api/v2010/account/incoming_phone_number/assigned_add_on/test_assigned_add_on_extension.py +++ /dev/null @@ -1,130 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class AssignedAddOnExtensionTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assigned_add_ons(sid="XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .extensions(sid="XFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IncomingPhoneNumbers/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AssignedAddOns/XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Extensions/XFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "XFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assigned_add_on_sid": "XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "resource_sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Incoming Voice Call", - "product_name": "Programmable Voice", - "unique_name": "voice-incoming", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions/XFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "enabled": true - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assigned_add_ons(sid="XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .extensions(sid="XFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assigned_add_ons(sid="XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .extensions.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IncomingPhoneNumbers/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AssignedAddOns/XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Extensions.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions.json?PageSize=50&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "extensions": [ - { - "sid": "XFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assigned_add_on_sid": "XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "resource_sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Incoming Voice Call", - "product_name": "Programmable Voice", - "unique_name": "voice-incoming", - "enabled": true, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions/XFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assigned_add_ons(sid="XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .extensions.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions.json?PageSize=50&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "extensions": [], - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assigned_add_ons(sid="XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .extensions.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/incoming_phone_number/test_assigned_add_on.py b/tests/integration/api/v2010/account/incoming_phone_number/test_assigned_add_on.py deleted file mode 100644 index 7cf0c16f90..0000000000 --- a/tests/integration/api/v2010/account/incoming_phone_number/test_assigned_add_on.py +++ /dev/null @@ -1,208 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class AssignedAddOnTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assigned_add_ons(sid="XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IncomingPhoneNumbers/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AssignedAddOns/XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "resource_sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "VoiceBase High Accuracy Transcription", - "description": "Automatic Transcription and Keyword Extract...", - "configuration": { - "bad_words": true - }, - "unique_name": "voicebase_high_accuracy_transcription", - "date_created": "Thu, 07 Apr 2016 23:52:28 +0000", - "date_updated": "Thu, 07 Apr 2016 23:52:28 +0000", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "subresource_uris": { - "extensions": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions.json" - } - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assigned_add_ons(sid="XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assigned_add_ons.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IncomingPhoneNumbers/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AssignedAddOns.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns.json?PageSize=50&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "assigned_add_ons": [ - { - "sid": "XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "resource_sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "VoiceBase High Accuracy Transcription", - "description": "Automatic Transcription and Keyword Extract...", - "configuration": { - "bad_words": true - }, - "unique_name": "voicebase_high_accuracy_transcription", - "date_created": "Thu, 07 Apr 2016 23:52:28 +0000", - "date_updated": "Thu, 07 Apr 2016 23:52:28 +0000", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "subresource_uris": { - "extensions": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions.json" - } - } - ], - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assigned_add_ons.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns.json?PageSize=50&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "assigned_add_ons": [], - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assigned_add_ons.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assigned_add_ons.create(installed_add_on_sid="XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = {'InstalledAddOnSid': "XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IncomingPhoneNumbers/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AssignedAddOns.json', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "resource_sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "VoiceBase High Accuracy Transcription", - "description": "Automatic Transcription and Keyword Extract...", - "configuration": { - "bad_words": true - }, - "unique_name": "voicebase_high_accuracy_transcription", - "date_created": "Thu, 07 Apr 2016 23:52:28 +0000", - "date_updated": "Thu, 07 Apr 2016 23:52:28 +0000", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "subresource_uris": { - "extensions": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions.json" - } - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assigned_add_ons.create(installed_add_on_sid="XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assigned_add_ons(sid="XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IncomingPhoneNumbers/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AssignedAddOns/XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assigned_add_ons(sid="XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/api/v2010/account/incoming_phone_number/test_local.py b/tests/integration/api/v2010/account/incoming_phone_number/test_local.py deleted file mode 100644 index fccc14a65c..0000000000 --- a/tests/integration/api/v2010/account/incoming_phone_number/test_local.py +++ /dev/null @@ -1,180 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class LocalTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers \ - .local.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IncomingPhoneNumbers/Local.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/Local.json?PageSize=1&Page=0", - "incoming_phone_numbers": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "address_requirements": "none", - "address_sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "beta": null, - "capabilities": { - "mms": true, - "sms": false, - "voice": true - }, - "date_created": "Thu, 30 Jul 2015 23:19:04 +0000", - "date_updated": "Thu, 30 Jul 2015 23:19:04 +0000", - "friendly_name": "(808) 925-5327", - "identity_sid": "RIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "phone_number": "+18089255327", - "origin": "origin", - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sms_application_sid": "", - "sms_fallback_method": "POST", - "sms_fallback_url": "", - "sms_method": "POST", - "sms_url": "", - "status_callback": "", - "status_callback_method": "POST", - "trunk_sid": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "voice_application_sid": "", - "voice_caller_id_lookup": false, - "voice_fallback_method": "POST", - "voice_fallback_url": null, - "voice_method": "POST", - "voice_url": null - } - ], - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/Local.json?PageSize=1&Page=2", - "next_page_uri": null, - "num_pages": 3, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 3, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/Local.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers \ - .local.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/Local.json?PageSize=1&Page=0", - "incoming_phone_numbers": [], - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/Local.json?PageSize=1&Page=2", - "next_page_uri": null, - "num_pages": 3, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 3, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/Local.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers \ - .local.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers \ - .local.create(phone_number="+15017122661") - - values = {'PhoneNumber': "+15017122661", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IncomingPhoneNumbers/Local.json', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "address_requirements": "none", - "address_sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "beta": false, - "capabilities": { - "mms": true, - "sms": false, - "voice": true - }, - "date_created": "Thu, 30 Jul 2015 23:19:04 +0000", - "date_updated": "Thu, 30 Jul 2015 23:19:04 +0000", - "friendly_name": "(808) 925-5327", - "identity_sid": "RIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "phone_number": "+18089255327", - "origin": "origin", - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sms_application_sid": "", - "sms_fallback_method": "POST", - "sms_fallback_url": "", - "sms_method": "POST", - "sms_url": "", - "status_callback": "", - "status_callback_method": "POST", - "trunk_sid": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "voice_application_sid": "", - "voice_caller_id_lookup": false, - "voice_fallback_method": "POST", - "voice_fallback_url": null, - "voice_method": "POST", - "voice_url": null - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers \ - .local.create(phone_number="+15017122661") - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/incoming_phone_number/test_mobile.py b/tests/integration/api/v2010/account/incoming_phone_number/test_mobile.py deleted file mode 100644 index c712ae615c..0000000000 --- a/tests/integration/api/v2010/account/incoming_phone_number/test_mobile.py +++ /dev/null @@ -1,180 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class MobileTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers \ - .mobile.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IncomingPhoneNumbers/Mobile.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/Mobile.json?Page=0&PageSize=50", - "incoming_phone_numbers": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "address_requirements": "none", - "address_sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "beta": null, - "capabilities": { - "mms": false, - "sms": true, - "voice": false - }, - "date_created": "Tue, 08 Sep 2015 16:21:16 +0000", - "date_updated": "Tue, 08 Sep 2015 16:21:16 +0000", - "friendly_name": "61429099450", - "identity_sid": "RIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "phone_number": "+61429099450", - "origin": "origin", - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sms_application_sid": "", - "sms_fallback_method": "POST", - "sms_fallback_url": "", - "sms_method": "POST", - "sms_url": "", - "status_callback": "", - "status_callback_method": "POST", - "trunk_sid": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "voice_application_sid": "", - "voice_caller_id_lookup": false, - "voice_fallback_method": "POST", - "voice_fallback_url": null, - "voice_method": "POST", - "voice_url": null - } - ], - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/Mobile.json?Page=0&PageSize=50", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/Mobile.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers \ - .mobile.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/Mobile.json?Page=0&PageSize=50", - "incoming_phone_numbers": [], - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/Mobile.json?Page=0&PageSize=50", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/Mobile.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers \ - .mobile.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers \ - .mobile.create(phone_number="+15017122661") - - values = {'PhoneNumber': "+15017122661", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IncomingPhoneNumbers/Mobile.json', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "address_requirements": "none", - "address_sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "beta": false, - "capabilities": { - "mms": true, - "sms": false, - "voice": true - }, - "date_created": "Thu, 30 Jul 2015 23:19:04 +0000", - "date_updated": "Thu, 30 Jul 2015 23:19:04 +0000", - "identity_sid": "RIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "(808) 925-5327", - "phone_number": "+18089255327", - "origin": "origin", - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sms_application_sid": "", - "sms_fallback_method": "POST", - "sms_fallback_url": "", - "sms_method": "POST", - "sms_url": "", - "status_callback": "", - "status_callback_method": "POST", - "trunk_sid": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "voice_application_sid": "", - "voice_caller_id_lookup": false, - "voice_fallback_method": "POST", - "voice_fallback_url": null, - "voice_method": "POST", - "voice_url": null - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers \ - .mobile.create(phone_number="+15017122661") - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/incoming_phone_number/test_toll_free.py b/tests/integration/api/v2010/account/incoming_phone_number/test_toll_free.py deleted file mode 100644 index af8a7e69d1..0000000000 --- a/tests/integration/api/v2010/account/incoming_phone_number/test_toll_free.py +++ /dev/null @@ -1,180 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class TollFreeTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers \ - .toll_free.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IncomingPhoneNumbers/TollFree.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/TollFree.json?PageSize=1&Page=0", - "incoming_phone_numbers": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "address_requirements": "none", - "address_sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "beta": null, - "capabilities": { - "mms": true, - "sms": false, - "voice": true - }, - "date_created": "Thu, 30 Jul 2015 23:19:04 +0000", - "date_updated": "Thu, 30 Jul 2015 23:19:04 +0000", - "friendly_name": "(808) 925-5327", - "identity_sid": "RIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "phone_number": "+18089255327", - "origin": "origin", - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sms_application_sid": "", - "sms_fallback_method": "POST", - "sms_fallback_url": "", - "sms_method": "POST", - "sms_url": "", - "status_callback": "", - "status_callback_method": "POST", - "trunk_sid": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "voice_application_sid": "", - "voice_caller_id_lookup": false, - "voice_fallback_method": "POST", - "voice_fallback_url": null, - "voice_method": "POST", - "voice_url": null - } - ], - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/TollFree.json?PageSize=1&Page=2", - "next_page_uri": null, - "num_pages": 3, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 3, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/TollFree.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers \ - .toll_free.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/TollFree.json?PageSize=1&Page=0", - "incoming_phone_numbers": [], - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/TollFree.json?PageSize=1&Page=2", - "next_page_uri": null, - "num_pages": 3, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 3, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/TollFree.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers \ - .toll_free.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers \ - .toll_free.create(phone_number="+15017122661") - - values = {'PhoneNumber': "+15017122661", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IncomingPhoneNumbers/TollFree.json', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "address_requirements": "none", - "address_sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "beta": false, - "capabilities": { - "mms": true, - "sms": false, - "voice": true - }, - "date_created": "Thu, 30 Jul 2015 23:19:04 +0000", - "date_updated": "Thu, 30 Jul 2015 23:19:04 +0000", - "friendly_name": "(808) 925-5327", - "identity_sid": "RIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "phone_number": "+18089255327", - "origin": "origin", - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sms_application_sid": "", - "sms_fallback_method": "POST", - "sms_fallback_url": "", - "sms_method": "POST", - "sms_url": "", - "status_callback": "", - "status_callback_method": "POST", - "trunk_sid": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "voice_application_sid": "", - "voice_caller_id_lookup": false, - "voice_fallback_method": "POST", - "voice_fallback_url": null, - "voice_method": "POST", - "voice_url": null - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers \ - .toll_free.create(phone_number="+15017122661") - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/message/__init__.py b/tests/integration/api/v2010/account/message/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/api/v2010/account/message/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/api/v2010/account/message/test_feedback.py b/tests/integration/api/v2010/account/message/test_feedback.py deleted file mode 100644 index 11264ab7c1..0000000000 --- a/tests/integration/api/v2010/account/message/test_feedback.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class FeedbackTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .feedback.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Feedback.json', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Thu, 30 Jul 2015 20:00:00 +0000", - "date_updated": "Thu, 30 Jul 2015 20:00:00 +0000", - "message_sid": "MMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "outcome": "confirmed", - "uri": "uri" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .feedback.create() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/message/test_media.py b/tests/integration/api/v2010/account/message/test_media.py deleted file mode 100644 index 6d705e0cbd..0000000000 --- a/tests/integration/api/v2010/account/message/test_media.py +++ /dev/null @@ -1,152 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class MediaTestCase(IntegrationTestCase): - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .media(sid="MEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Media/MEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .media(sid="MEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .media(sid="MEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Media/MEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "content_type": "image/jpeg", - "date_created": "Sun, 16 Aug 2015 15:53:54 +0000", - "date_updated": "Sun, 16 Aug 2015 15:53:55 +0000", - "parent_sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "MEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media/MEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .media(sid="MEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .media.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Media.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media.json?PageSize=50&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media.json?PageSize=50&Page=0", - "media_list": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "content_type": "image/jpeg", - "date_created": "Sun, 16 Aug 2015 15:53:54 +0000", - "date_updated": "Sun, 16 Aug 2015 15:53:55 +0000", - "parent_sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "MEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media/MEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .media.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media.json?PageSize=50&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media.json?PageSize=50&Page=0", - "media_list": [], - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .media.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/queue/__init__.py b/tests/integration/api/v2010/account/queue/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/api/v2010/account/queue/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/api/v2010/account/queue/test_member.py b/tests/integration/api/v2010/account/queue/test_member.py deleted file mode 100644 index 92acab2916..0000000000 --- a/tests/integration/api/v2010/account/queue/test_member.py +++ /dev/null @@ -1,159 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class MemberTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues(sid="QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(call_sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Queues/QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_enqueued": "Tue, 07 Aug 2012 22:57:41 +0000", - "position": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues/QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "wait_time": 143 - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues(sid="QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(call_sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues(sid="QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(call_sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(url="https://example.com", method="GET") - - values = {'Url': "https://example.com", 'Method': "GET", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Queues/QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_enqueued": "Tue, 07 Aug 2012 22:57:41 +0000", - "position": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues/QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "wait_time": 143 - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues(sid="QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(call_sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(url="https://example.com", method="GET") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues(sid="QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Queues/QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues/QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members.json?Page=0&PageSize=50", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues/QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members.json?Page=0&PageSize=50", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "queue_members": [ - { - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_enqueued": "Tue, 07 Aug 2012 22:57:41 +0000", - "position": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues/QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "wait_time": 124 - } - ], - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues/QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues(sid="QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues/QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members.json?Page=0&PageSize=50", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues/QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members.json?Page=0&PageSize=50", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "queue_members": [], - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues/QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues(sid="QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/recording/__init__.py b/tests/integration/api/v2010/account/recording/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/api/v2010/account/recording/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/api/v2010/account/recording/add_on_result/__init__.py b/tests/integration/api/v2010/account/recording/add_on_result/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/api/v2010/account/recording/add_on_result/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/api/v2010/account/recording/add_on_result/test_payload.py b/tests/integration/api/v2010/account/recording/add_on_result/test_payload.py deleted file mode 100644 index 32c5c2a406..0000000000 --- a/tests/integration/api/v2010/account/recording/add_on_result/test_payload.py +++ /dev/null @@ -1,165 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class PayloadTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .add_on_results(sid="XRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .payloads(sid="XHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings/REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AddOnResults/XRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Payloads/XHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "XHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reference_sid": "REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "add_on_sid": "XBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "add_on_configuration_sid": "XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "add_on_result_sid": "XRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "label": "XHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "content_type": "application/json", - "date_created": "Wed, 01 Sep 2010 15:15:41 +0000", - "date_updated": "Wed, 01 Sep 2010 15:15:41 +0000", - "subresource_uris": { - "data": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AddOnResults/XRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Payloads/XHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Data.json" - } - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .add_on_results(sid="XRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .payloads(sid="XHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .add_on_results(sid="XRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .payloads.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings/REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AddOnResults/XRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Payloads.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AddOnResults/XRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Payloads.json?PageSize=50&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "payloads": [ - { - "sid": "XHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reference_sid": "REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "add_on_sid": "XBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "add_on_configuration_sid": "XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "add_on_result_sid": "XRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "label": "XHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "content_type": "application/json", - "date_created": "Wed, 01 Sep 2010 15:15:41 +0000", - "date_updated": "Wed, 01 Sep 2010 15:15:41 +0000", - "subresource_uris": { - "data": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AddOnResults/XRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Payloads/XHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Data.json" - } - } - ], - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AddOnResults/XRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Payloads.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .add_on_results(sid="XRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .payloads.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AddOnResults/XRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Payloads.json?PageSize=50&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "payloads": [], - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AddOnResults/XRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Payloads.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .add_on_results(sid="XRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .payloads.list() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .add_on_results(sid="XRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .payloads(sid="XHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings/REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AddOnResults/XRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Payloads/XHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .add_on_results(sid="XRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .payloads(sid="XHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/api/v2010/account/recording/test_add_on_result.py b/tests/integration/api/v2010/account/recording/test_add_on_result.py deleted file mode 100644 index 20aeffed03..0000000000 --- a/tests/integration/api/v2010/account/recording/test_add_on_result.py +++ /dev/null @@ -1,156 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class AddOnResultTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .add_on_results(sid="XRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings/REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AddOnResults/XRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "XRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reference_sid": "REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "completed", - "add_on_sid": "XBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "add_on_configuration_sid": "XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Wed, 01 Sep 2010 15:15:41 +0000", - "date_updated": "Wed, 01 Sep 2010 15:15:41 +0000", - "date_completed": "Wed, 01 Sep 2010 15:15:41 +0000", - "subresource_uris": { - "payloads": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AddOnResults/XRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Payloads.json" - } - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .add_on_results(sid="XRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .add_on_results.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings/REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AddOnResults.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AddOnResults.json?PageSize=50&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "add_on_results": [ - { - "sid": "XRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reference_sid": "REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "completed", - "add_on_sid": "XBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "add_on_configuration_sid": "XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Wed, 01 Sep 2010 15:15:41 +0000", - "date_updated": "Wed, 01 Sep 2010 15:15:41 +0000", - "date_completed": "Wed, 01 Sep 2010 15:15:41 +0000", - "subresource_uris": { - "payloads": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AddOnResults/XRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Payloads.json" - } - } - ], - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AddOnResults.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .add_on_results.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AddOnResults.json?PageSize=50&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "add_on_results": [], - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AddOnResults.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .add_on_results.list() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .add_on_results(sid="XRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings/REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AddOnResults/XRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .add_on_results(sid="XRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/api/v2010/account/recording/test_transcription.py b/tests/integration/api/v2010/account/recording/test_transcription.py deleted file mode 100644 index bebfac5527..0000000000 --- a/tests/integration/api/v2010/account/recording/test_transcription.py +++ /dev/null @@ -1,164 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class TranscriptionTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .transcriptions(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings/REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Transcriptions/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2008-08-01", - "date_created": "Mon, 22 Aug 2011 20:58:44 +0000", - "date_updated": "Mon, 22 Aug 2011 20:58:44 +0000", - "duration": "10", - "price": "0.00000", - "price_unit": "USD", - "recording_sid": "REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "in-progress", - "transcription_text": "THIS IS A TEST", - "type": "fast", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .transcriptions(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .transcriptions(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings/REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Transcriptions/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .transcriptions(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .transcriptions.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings/REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Transcriptions.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json?PageSize=50&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json?PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "transcriptions": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2008-08-01", - "date_created": "Mon, 22 Aug 2011 20:58:44 +0000", - "date_updated": "Mon, 22 Aug 2011 20:58:44 +0000", - "duration": "10", - "price": "0.00000", - "price_unit": "USD", - "recording_sid": "REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "in-progress", - "transcription_text": "THIS IS A TEST", - "type": "fast", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .transcriptions.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json?PageSize=50&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json?PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "transcriptions": [], - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .transcriptions.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/sip/__init__.py b/tests/integration/api/v2010/account/sip/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/api/v2010/account/sip/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/api/v2010/account/sip/credential_list/__init__.py b/tests/integration/api/v2010/account/sip/credential_list/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/api/v2010/account/sip/credential_list/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/api/v2010/account/sip/credential_list/test_credential.py b/tests/integration/api/v2010/account/sip/credential_list/test_credential.py deleted file mode 100644 index 328ffc5299..0000000000 --- a/tests/integration/api/v2010/account/sip/credential_list/test_credential.py +++ /dev/null @@ -1,236 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class CredentialTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists(sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/CredentialLists/CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Credentials.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "credentials": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "credential_list_sid": "CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Wed, 19 Aug 2015 19:48:45 +0000", - "date_updated": "Wed, 19 Aug 2015 19:48:45 +0000", - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "username": "1440013725.28" - } - ], - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Credentials.json?PageSize=50&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Credentials.json?PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Credentials.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists(sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "credentials": [], - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Credentials.json?PageSize=50&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Credentials.json?PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Credentials.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists(sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists(sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials.create(username="username", password="password") - - values = {'Username': "username", 'Password': "password", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/CredentialLists/CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Credentials.json', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "credential_list_sid": "CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Wed, 19 Aug 2015 19:48:45 +0000", - "date_updated": "Wed, 19 Aug 2015 19:48:45 +0000", - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "username": "1440013725.28" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists(sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials.create(username="username", password="password") - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists(sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/CredentialLists/CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "credential_list_sid": "CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Wed, 19 Aug 2015 19:48:45 +0000", - "date_updated": "Wed, 19 Aug 2015 19:48:45 +0000", - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "username": "1440013725.28" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists(sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists(sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/CredentialLists/CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "credential_list_sid": "CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Wed, 19 Aug 2015 19:48:45 +0000", - "date_updated": "Wed, 19 Aug 2015 19:48:45 +0000", - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "username": "1440013725.28" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists(sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists(sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/CredentialLists/CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists(sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/api/v2010/account/sip/domain/__init__.py b/tests/integration/api/v2010/account/sip/domain/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/api/v2010/account/sip/domain/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/api/v2010/account/sip/domain/test_credential_list_mapping.py b/tests/integration/api/v2010/account/sip/domain/test_credential_list_mapping.py deleted file mode 100644 index ef77eb54d7..0000000000 --- a/tests/integration/api/v2010/account/sip/domain/test_credential_list_mapping.py +++ /dev/null @@ -1,195 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class CredentialListMappingTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains(sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credential_list_mappings.create(credential_list_sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = {'CredentialListSid': "CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/Domains/SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/CredentialListMappings.json', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Wed, 11 Sep 2013 17:51:38 -0000", - "date_updated": "Wed, 11 Sep 2013 17:51:38 -0000", - "friendly_name": "Production Gateways IP Address - Scranton", - "sid": "CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "subresource_uris": { - "credentials": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Credentials.json" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains(sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credential_list_mappings.create(credential_list_sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains(sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credential_list_mappings.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/Domains/SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/CredentialListMappings.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "credential_list_mappings": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Wed, 11 Sep 2013 17:51:38 -0000", - "date_updated": "Wed, 11 Sep 2013 17:51:38 -0000", - "friendly_name": "Production Gateways IP Address - Scranton", - "sid": "CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "subresource_uris": { - "credentials": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Credentials.json" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialListMappings.json?PageSize=50&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialListMappings.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains(sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credential_list_mappings.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "credential_list_mappings": [], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialListMappings.json?PageSize=50&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialListMappings.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains(sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credential_list_mappings.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains(sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credential_list_mappings(sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/Domains/SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/CredentialListMappings/CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Wed, 11 Sep 2013 17:51:38 -0000", - "date_updated": "Wed, 11 Sep 2013 17:51:38 -0000", - "friendly_name": "Production Gateways IP Address - Scranton", - "sid": "CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "subresource_uris": { - "credentials": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Credentials.json" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains(sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credential_list_mappings(sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains(sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credential_list_mappings(sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/Domains/SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/CredentialListMappings/CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains(sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credential_list_mappings(sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/api/v2010/account/sip/domain/test_ip_access_control_list_mapping.py b/tests/integration/api/v2010/account/sip/domain/test_ip_access_control_list_mapping.py deleted file mode 100644 index 03ffed4fd3..0000000000 --- a/tests/integration/api/v2010/account/sip/domain/test_ip_access_control_list_mapping.py +++ /dev/null @@ -1,205 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class IpAccessControlListMappingTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains(sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_list_mappings(sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/Domains/SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IpAccessControlListMappings/ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Fri, 17 Jul 2015 21:25:15 +0000", - "date_updated": "Fri, 17 Jul 2015 21:25:15 +0000", - "friendly_name": "aaaa", - "sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "subresource_uris": { - "ip_addresses": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses.json" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlListMappings/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains(sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_list_mappings(sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains(sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_list_mappings.create(ip_access_control_list_sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = {'IpAccessControlListSid': "ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/Domains/SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IpAccessControlListMappings.json', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Fri, 17 Jul 2015 21:25:15 +0000", - "date_updated": "Fri, 17 Jul 2015 21:25:15 +0000", - "friendly_name": "aaaa", - "sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "subresource_uris": { - "ip_addresses": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses.json" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlListMappings/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains(sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_list_mappings.create(ip_access_control_list_sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains(sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_list_mappings.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/Domains/SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IpAccessControlListMappings.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlListMappings.json?SipDomainSid=SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0", - "ip_access_control_list_mappings": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Fri, 17 Jul 2015 21:25:15 +0000", - "date_updated": "Fri, 17 Jul 2015 21:25:15 +0000", - "friendly_name": "aaaa", - "sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "subresource_uris": { - "ip_addresses": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses.json" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlListMappings.json?SipDomainSid=SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlListMappings.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains(sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_list_mappings.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlListMappings.json?SipDomainSid=SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0", - "ip_access_control_list_mappings": [], - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlListMappings.json?SipDomainSid=SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlListMappings.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains(sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_list_mappings.list() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains(sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_list_mappings(sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/Domains/SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IpAccessControlListMappings/ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains(sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_list_mappings(sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/api/v2010/account/sip/ip_access_control_list/__init__.py b/tests/integration/api/v2010/account/sip/ip_access_control_list/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/api/v2010/account/sip/ip_access_control_list/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/api/v2010/account/sip/ip_access_control_list/test_ip_address.py b/tests/integration/api/v2010/account/sip/ip_access_control_list/test_ip_address.py deleted file mode 100644 index 0167c934f6..0000000000 --- a/tests/integration/api/v2010/account/sip/ip_access_control_list/test_ip_address.py +++ /dev/null @@ -1,240 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class IpAddressTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists(sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_addresses.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/IpAccessControlLists/ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IpAddresses.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses.json?PageSize=50&Page=0", - "ip_addresses": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Mon, 20 Jul 2015 17:27:10 +0000", - "date_updated": "Mon, 20 Jul 2015 17:27:10 +0000", - "friendly_name": "aaa", - "ip_access_control_list_sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ip_address": "192.1.1.2", - "sid": "IPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses/IPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses.json?PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists(sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_addresses.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses.json?PageSize=50&Page=0", - "ip_addresses": [], - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses.json?PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists(sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_addresses.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists(sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_addresses.create(friendly_name="friendly_name", ip_address="ip_address") - - values = {'FriendlyName': "friendly_name", 'IpAddress': "ip_address", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/IpAccessControlLists/ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IpAddresses.json', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Mon, 20 Jul 2015 17:27:10 +0000", - "date_updated": "Mon, 20 Jul 2015 17:27:10 +0000", - "friendly_name": "aaa", - "ip_access_control_list_sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ip_address": "192.1.1.2", - "sid": "IPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses/IPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists(sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_addresses.create(friendly_name="friendly_name", ip_address="ip_address") - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists(sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_addresses(sid="IPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/IpAccessControlLists/ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IpAddresses/IPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Mon, 20 Jul 2015 17:27:10 +0000", - "date_updated": "Mon, 20 Jul 2015 17:27:10 +0000", - "friendly_name": "aaa", - "ip_access_control_list_sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ip_address": "192.1.1.2", - "sid": "IPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses/IPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists(sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_addresses(sid="IPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists(sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_addresses(sid="IPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/IpAccessControlLists/ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IpAddresses/IPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Mon, 20 Jul 2015 17:27:10 +0000", - "date_updated": "Mon, 20 Jul 2015 17:27:10 +0000", - "friendly_name": "aaa", - "ip_access_control_list_sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ip_address": "192.1.1.2", - "sid": "IPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses/IPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists(sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_addresses(sid="IPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists(sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_addresses(sid="IPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/IpAccessControlLists/ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IpAddresses/IPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists(sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_addresses(sid="IPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/api/v2010/account/sip/test_credential_list.py b/tests/integration/api/v2010/account/sip/test_credential_list.py deleted file mode 100644 index 17f4c44291..0000000000 --- a/tests/integration/api/v2010/account/sip/test_credential_list.py +++ /dev/null @@ -1,226 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class CredentialListTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/CredentialLists.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "credential_lists": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Wed, 11 Sep 2013 17:51:38 -0000", - "date_updated": "Wed, 11 Sep 2013 17:51:38 -0000", - "friendly_name": "Low Rises", - "sid": "CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "subresource_uris": { - "credentials": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Credentials.json" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists.json?PageSize=50&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "credential_lists": [], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists.json?PageSize=50&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists.create(friendly_name="friendly_name") - - values = {'FriendlyName': "friendly_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/CredentialLists.json', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Wed, 11 Sep 2013 17:51:38 -0000", - "date_updated": "Wed, 11 Sep 2013 17:51:38 -0000", - "friendly_name": "Low Rises", - "sid": "CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "subresource_uris": { - "credentials": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Credentials.json" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists.create(friendly_name="friendly_name") - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists(sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/CredentialLists/CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Wed, 11 Sep 2013 17:51:38 -0000", - "date_updated": "Wed, 11 Sep 2013 17:51:38 -0000", - "friendly_name": "Low Rises", - "sid": "CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "subresource_uris": { - "credentials": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Credentials.json" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists(sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists(sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(friendly_name="friendly_name") - - values = {'FriendlyName': "friendly_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/CredentialLists/CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Wed, 11 Sep 2013 17:51:38 -0000", - "date_updated": "Wed, 11 Sep 2013 17:51:38 -0000", - "friendly_name": "Low Rises", - "sid": "CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "subresource_uris": { - "credentials": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Credentials.json" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists(sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(friendly_name="friendly_name") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists(sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/CredentialLists/CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists(sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/api/v2010/account/sip/test_domain.py b/tests/integration/api/v2010/account/sip/test_domain.py deleted file mode 100644 index 817696a177..0000000000 --- a/tests/integration/api/v2010/account/sip/test_domain.py +++ /dev/null @@ -1,267 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class DomainTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/Domains.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "domains": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "auth_type": "", - "date_created": "Fri, 06 Sep 2013 18:48:50 -0000", - "date_updated": "Fri, 06 Sep 2013 18:48:50 -0000", - "domain_name": "dunder-mifflin-scranton.api.twilio.com", - "friendly_name": "Scranton Office", - "sip_registration": true, - "sid": "SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "subresource_uris": { - "credential_list_mappings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialListMappings.json", - "ip_access_control_list_mappings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlListMappings.json" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "voice_fallback_method": "POST", - "voice_fallback_url": null, - "voice_method": "POST", - "voice_status_callback_method": "POST", - "voice_status_callback_url": null, - "voice_url": "https://dundermifflin.example.com/twilio/app.php" - } - ], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains.json?PageSize=50&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "domains": [], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains.json?PageSize=50&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains.create(domain_name="domain_name") - - values = {'DomainName': "domain_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/Domains.json', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "auth_type": "IP_ACL", - "date_created": "Fri, 06 Sep 2013 19:18:30 -0000", - "date_updated": "Fri, 06 Sep 2013 19:18:30 -0000", - "domain_name": "dunder-mifflin-scranton.sip.twilio.com", - "friendly_name": "Scranton Office", - "sip_registration": true, - "sid": "SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "subresource_uris": { - "credential_list_mappings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialListMappings.json", - "ip_access_control_list_mappings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlListMappings.json" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "voice_fallback_method": "POST", - "voice_fallback_url": null, - "voice_method": "POST", - "voice_status_callback_method": "POST", - "voice_status_callback_url": null, - "voice_url": "https://dundermifflin.example.com/twilio/app.php" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains.create(domain_name="domain_name") - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains(sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/Domains/SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "auth_type": "IP_ACL", - "date_created": "Fri, 06 Sep 2013 19:18:30 -0000", - "date_updated": "Fri, 06 Sep 2013 19:18:30 -0000", - "domain_name": "dunder-mifflin-scranton.sip.twilio.com", - "friendly_name": "Scranton Office", - "sip_registration": true, - "sid": "SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "subresource_uris": { - "credential_list_mappings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialListMappings.json", - "ip_access_control_list_mappings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlListMappings.json" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "voice_fallback_method": "POST", - "voice_fallback_url": null, - "voice_method": "POST", - "voice_status_callback_method": "POST", - "voice_status_callback_url": null, - "voice_url": "https://dundermifflin.example.com/twilio/app.php" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains(sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains(sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/Domains/SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "auth_type": "IP_ACL", - "date_created": "Fri, 06 Sep 2013 19:18:30 -0000", - "date_updated": "Fri, 06 Sep 2013 19:18:30 -0000", - "domain_name": "dunder-mifflin-scranton.sip.twilio.com", - "friendly_name": "Scranton Office", - "sip_registration": false, - "sid": "SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "subresource_uris": { - "credential_list_mappings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialListMappings.json", - "ip_access_control_list_mappings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlListMappings.json" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "voice_fallback_method": "POST", - "voice_fallback_url": null, - "voice_method": "POST", - "voice_status_callback_method": "POST", - "voice_status_callback_url": null, - "voice_url": "https://dundermifflin.example.com/twilio/app.php" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains(sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains(sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/Domains/SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains(sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/api/v2010/account/sip/test_ip_access_control_list.py b/tests/integration/api/v2010/account/sip/test_ip_access_control_list.py deleted file mode 100644 index 2aa3dd311e..0000000000 --- a/tests/integration/api/v2010/account/sip/test_ip_access_control_list.py +++ /dev/null @@ -1,236 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class IpAccessControlListTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/IpAccessControlLists.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists.json?PageSize=50&Page=0", - "ip_access_control_lists": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Fri, 17 Jul 2015 21:25:15 +0000", - "date_updated": "Fri, 17 Jul 2015 21:25:15 +0000", - "friendly_name": "aaaa", - "sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "subresource_uris": { - "ip_addresses": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses.json" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists.json?PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists.json?PageSize=50&Page=0", - "ip_access_control_lists": [], - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists.json?PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists.create(friendly_name="friendly_name") - - values = {'FriendlyName': "friendly_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/IpAccessControlLists.json', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Fri, 17 Jul 2015 21:25:15 +0000", - "date_updated": "Fri, 17 Jul 2015 21:25:15 +0000", - "friendly_name": "aaaa", - "sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "subresource_uris": { - "ip_addresses": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses.json" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists.create(friendly_name="friendly_name") - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists(sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/IpAccessControlLists/ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Fri, 17 Jul 2015 21:25:15 +0000", - "date_updated": "Fri, 17 Jul 2015 21:25:15 +0000", - "friendly_name": "aaaa", - "sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "subresource_uris": { - "ip_addresses": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses.json" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists(sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists(sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(friendly_name="friendly_name") - - values = {'FriendlyName': "friendly_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/IpAccessControlLists/ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Fri, 17 Jul 2015 21:25:15 +0000", - "date_updated": "Fri, 17 Jul 2015 21:25:15 +0000", - "friendly_name": "aaaa", - "sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "subresource_uris": { - "ip_addresses": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses.json" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists(sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(friendly_name="friendly_name") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists(sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/IpAccessControlLists/ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists(sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/api/v2010/account/test_address.py b/tests/integration/api/v2010/account/test_address.py deleted file mode 100644 index d7fb63fca0..0000000000 --- a/tests/integration/api/v2010/account/test_address.py +++ /dev/null @@ -1,249 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class AddressTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .addresses.create(customer_name="customer_name", street="street", city="city", region="region", postal_code="postal_code", iso_country="US") - - values = { - 'CustomerName': "customer_name", - 'Street': "street", - 'City': "city", - 'Region': "region", - 'PostalCode': "postal_code", - 'IsoCountry': "US", - } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Addresses.json', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "city": "SF", - "customer_name": "name", - "date_created": "Tue, 18 Aug 2015 17:07:30 +0000", - "date_updated": "Tue, 18 Aug 2015 17:07:30 +0000", - "emergency_enabled": false, - "friendly_name": null, - "iso_country": "US", - "postal_code": "94019", - "region": "CA", - "sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "street": "4th", - "validated": false, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Addresses/ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .addresses.create(customer_name="customer_name", street="street", city="city", region="region", postal_code="postal_code", iso_country="US") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .addresses(sid="ADXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Addresses/ADXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .addresses(sid="ADXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .addresses(sid="ADXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Addresses/ADXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "city": "SF", - "customer_name": "name", - "date_created": "Tue, 18 Aug 2015 17:07:30 +0000", - "date_updated": "Tue, 18 Aug 2015 17:07:30 +0000", - "emergency_enabled": false, - "friendly_name": null, - "iso_country": "US", - "postal_code": "94019", - "region": "CA", - "sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "street": "4th", - "validated": false, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Addresses/ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .addresses(sid="ADXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .addresses(sid="ADXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Addresses/ADXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "city": "SF", - "customer_name": "name", - "date_created": "Tue, 18 Aug 2015 17:07:30 +0000", - "date_updated": "Tue, 18 Aug 2015 17:07:30 +0000", - "emergency_enabled": false, - "friendly_name": null, - "iso_country": "US", - "postal_code": "94019", - "region": "CA", - "sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "street": "4th", - "validated": false, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Addresses/ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .addresses(sid="ADXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .addresses.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Addresses.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "addresses": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "city": "SF", - "customer_name": "name", - "date_created": "Tue, 18 Aug 2015 17:07:30 +0000", - "date_updated": "Tue, 18 Aug 2015 17:07:30 +0000", - "emergency_enabled": false, - "friendly_name": null, - "iso_country": "US", - "postal_code": "94019", - "region": "CA", - "sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "street": "4th", - "validated": false, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Addresses/ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Addresses.json?PageSize=50&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Addresses.json?PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Addresses.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .addresses.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "addresses": [], - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Addresses.json?PageSize=50&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Addresses.json?PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Addresses.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .addresses.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/test_application.py b/tests/integration/api/v2010/account/test_application.py deleted file mode 100644 index 5e0f69c72b..0000000000 --- a/tests/integration/api/v2010/account/test_application.py +++ /dev/null @@ -1,266 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ApplicationTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .applications.create(friendly_name="friendly_name") - - values = {'FriendlyName': "friendly_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Applications.json', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "date_created": "Mon, 22 Aug 2011 20:59:45 +0000", - "date_updated": "Tue, 18 Aug 2015 16:48:57 +0000", - "friendly_name": "Application Friendly Name", - "message_status_callback": "http://www.example.com/sms-status-callback", - "sid": "APaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sms_fallback_method": "GET", - "sms_fallback_url": "http://www.example.com/sms-fallback", - "sms_method": "GET", - "sms_status_callback": "http://www.example.com/sms-status-callback", - "sms_url": "http://example.com", - "status_callback": "http://example.com", - "status_callback_method": "GET", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Applications/APaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "voice_caller_id_lookup": false, - "voice_fallback_method": "GET", - "voice_fallback_url": "http://www.example.com/voice-callback", - "voice_method": "GET", - "voice_url": "http://example.com" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .applications.create(friendly_name="friendly_name") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .applications(sid="APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Applications/APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .applications(sid="APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .applications(sid="APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Applications/APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "date_created": "Mon, 22 Aug 2011 20:59:45 +0000", - "date_updated": "Tue, 18 Aug 2015 16:48:57 +0000", - "friendly_name": "Application Friendly Name", - "message_status_callback": "http://www.example.com/sms-status-callback", - "sid": "APaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sms_fallback_method": "GET", - "sms_fallback_url": "http://www.example.com/sms-fallback", - "sms_method": "GET", - "sms_status_callback": "http://www.example.com/sms-status-callback", - "sms_url": "http://example.com", - "status_callback": "http://example.com", - "status_callback_method": "GET", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Applications/APaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "voice_caller_id_lookup": false, - "voice_fallback_method": "GET", - "voice_fallback_url": "http://www.example.com/voice-callback", - "voice_method": "GET", - "voice_url": "http://example.com" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .applications(sid="APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .applications.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Applications.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "applications": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "date_created": "Fri, 21 Aug 2015 00:07:25 +0000", - "date_updated": "Fri, 21 Aug 2015 00:07:25 +0000", - "friendly_name": "d8821fb7-4d01-48b2-bdc5-34e46252b90b", - "message_status_callback": null, - "sid": "APaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sms_fallback_method": "POST", - "sms_fallback_url": null, - "sms_method": "POST", - "sms_status_callback": null, - "sms_url": null, - "status_callback": null, - "status_callback_method": "POST", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Applications/APaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "voice_caller_id_lookup": false, - "voice_fallback_method": "POST", - "voice_fallback_url": null, - "voice_method": "POST", - "voice_url": null - } - ], - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Applications.json?PageSize=1&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Applications.json?PageSize=1&Page=35", - "next_page_uri": null, - "num_pages": 36, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 36, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Applications.json?PageSize=1&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .applications.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "applications": [], - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Applications.json?PageSize=1&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Applications.json?PageSize=1&Page=35", - "next_page_uri": null, - "num_pages": 36, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 36, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Applications.json?PageSize=1&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .applications.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .applications(sid="APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Applications/APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "date_created": "Mon, 22 Aug 2011 20:59:45 +0000", - "date_updated": "Tue, 18 Aug 2015 16:48:57 +0000", - "friendly_name": "Application Friendly Name", - "message_status_callback": "http://www.example.com/sms-status-callback", - "sid": "APaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sms_fallback_method": "GET", - "sms_fallback_url": "http://www.example.com/sms-fallback", - "sms_method": "GET", - "sms_status_callback": "http://www.example.com/sms-status-callback", - "sms_url": "http://example.com", - "status_callback": "http://example.com", - "status_callback_method": "GET", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Applications/APaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "voice_caller_id_lookup": false, - "voice_fallback_method": "GET", - "voice_fallback_url": "http://www.example.com/voice-callback", - "voice_method": "GET", - "voice_url": "http://example.com" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .applications(sid="APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/test_authorized_connect_app.py b/tests/integration/api/v2010/account/test_authorized_connect_app.py deleted file mode 100644 index c7ff661c7c..0000000000 --- a/tests/integration/api/v2010/account/test_authorized_connect_app.py +++ /dev/null @@ -1,132 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class AuthorizedConnectAppTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .authorized_connect_apps(connect_app_sid="CNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AuthorizedConnectApps/CNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "connect_app_company_name": "aaa", - "connect_app_description": "alksjdfl;ajseifj;alsijfl;ajself;jasjfjas;lejflj", - "connect_app_friendly_name": "aaa", - "connect_app_homepage_url": "http://www.google.com", - "connect_app_sid": "CNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Tue, 31 Aug 2010 20:36:28 +0000", - "date_updated": "Tue, 31 Aug 2010 20:36:44 +0000", - "permissions": [ - "get-all" - ], - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AuthorizedConnectApps/CNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .authorized_connect_apps(connect_app_sid="CNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .authorized_connect_apps.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AuthorizedConnectApps.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "authorized_connect_apps": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "connect_app_company_name": "YOUR OTHER MOM", - "connect_app_description": "alksjdfl;ajseifj;alsijfl;ajself;jasjfjas;lejflj", - "connect_app_friendly_name": "YOUR MOM", - "connect_app_homepage_url": "http://www.google.com", - "connect_app_sid": "CNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Tue, 31 Aug 2010 20:36:28 +0000", - "date_updated": "Tue, 31 Aug 2010 20:36:44 +0000", - "permissions": [ - "get-all" - ], - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AuthorizedConnectApps/CNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AuthorizedConnectApps.json?Page=0&PageSize=50", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AuthorizedConnectApps.json?Page=0&PageSize=50", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AuthorizedConnectApps.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .authorized_connect_apps.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "authorized_connect_apps": [], - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AuthorizedConnectApps.json?Page=0&PageSize=50", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AuthorizedConnectApps.json?Page=0&PageSize=50", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AuthorizedConnectApps.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .authorized_connect_apps.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/test_available_phone_number.py b/tests/integration/api/v2010/account/test_available_phone_number.py deleted file mode 100644 index 14764ea0cf..0000000000 --- a/tests/integration/api/v2010/account/test_available_phone_number.py +++ /dev/null @@ -1,123 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class AvailablePhoneNumberCountryTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AvailablePhoneNumbers.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "countries": [ - { - "beta": false, - "country": "Denmark", - "country_code": "DK", - "subresource_uris": { - "local": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/DK/Local.json" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/DK.json" - } - ], - "end": 1, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/DK.json?PageSize=50&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/DK.json?PageSize=50&Page=0", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "countries": [], - "end": 1, - "first_page_uri": null, - "last_page_uri": null, - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers(country_code="US").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AvailablePhoneNumbers/US.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "beta": null, - "country": "United States", - "country_code": "US", - "subresource_uris": { - "local": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/Local.json", - "toll_free": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/TollFree.json" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers(country_code="US").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/test_call.py b/tests/integration/api/v2010/account/test_call.py deleted file mode 100644 index e5eeb3d87f..0000000000 --- a/tests/integration/api/v2010/account/test_call.py +++ /dev/null @@ -1,294 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class CallTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls.create(to="+15558675310", from_="+15017122661") - - values = {'To': "+15558675310", 'From': "+15017122661", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls.json', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "annotation": null, - "answered_by": null, - "api_version": "2010-04-01", - "caller_name": null, - "date_created": "Tue, 31 Aug 2010 20:36:28 +0000", - "date_updated": "Tue, 31 Aug 2010 20:36:44 +0000", - "direction": "inbound", - "duration": "15", - "end_time": "Tue, 31 Aug 2010 20:36:44 +0000", - "forwarded_from": "+141586753093", - "from": "+14158675308", - "from_formatted": "(415) 867-5308", - "group_sid": null, - "parent_call_sid": null, - "phone_number_sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "price": "-0.03000", - "price_unit": "USD", - "sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "start_time": "Tue, 31 Aug 2010 20:36:29 +0000", - "status": "completed", - "subresource_uris": { - "notifications": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json", - "recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json", - "feedback": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Feedback.json", - "feedback_summaries": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/FeedbackSummary.json" - }, - "to": "+14158675309", - "to_formatted": "(415) 867-5309", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls.create(to="+15558675310", from_="+15017122661") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "annotation": null, - "answered_by": null, - "api_version": "2010-04-01", - "caller_name": null, - "date_created": "Tue, 31 Aug 2010 20:36:28 +0000", - "date_updated": "Tue, 31 Aug 2010 20:36:44 +0000", - "direction": "inbound", - "duration": "15", - "end_time": "Tue, 31 Aug 2010 20:36:44 +0000", - "forwarded_from": "+141586753093", - "from": "+14158675308", - "from_formatted": "(415) 867-5308", - "group_sid": null, - "parent_call_sid": null, - "phone_number_sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "price": "-0.03000", - "price_unit": "USD", - "sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "start_time": "Tue, 31 Aug 2010 20:36:29 +0000", - "status": "completed", - "subresource_uris": { - "notifications": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json", - "recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json" - }, - "to": "+14158675309", - "to_formatted": "(415) 867-5309", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "calls": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "annotation": null, - "answered_by": null, - "api_version": "2010-04-01", - "caller_name": "", - "date_created": "Fri, 04 Sep 2015 22:48:30 +0000", - "date_updated": "Fri, 04 Sep 2015 22:48:35 +0000", - "direction": "outbound-api", - "duration": "0", - "end_time": "Fri, 04 Sep 2015 22:48:35 +0000", - "forwarded_from": null, - "from": "kevin", - "from_formatted": "kevin", - "group_sid": null, - "parent_call_sid": null, - "phone_number_sid": "", - "price": null, - "price_unit": "USD", - "sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "start_time": "Fri, 04 Sep 2015 22:48:31 +0000", - "status": "failed", - "subresource_uris": { - "notifications": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json", - "recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json" - }, - "to": "sip:kevin@example.com", - "to_formatted": "sip:kevin@example.com", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls.json?PageSize=1&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls.json?PageSize=1&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "calls": [], - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls.json?PageSize=1&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls.json?PageSize=1&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "annotation": null, - "answered_by": null, - "api_version": "2010-04-01", - "caller_name": null, - "date_created": "Tue, 31 Aug 2010 20:36:28 +0000", - "date_updated": "Tue, 31 Aug 2010 20:36:44 +0000", - "direction": "inbound", - "duration": "15", - "end_time": "Tue, 31 Aug 2010 20:36:44 +0000", - "forwarded_from": "+141586753093", - "from": "+14158675308", - "from_formatted": "(415) 867-5308", - "group_sid": null, - "parent_call_sid": null, - "phone_number_sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "price": "-0.03000", - "price_unit": "USD", - "sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "start_time": "Tue, 31 Aug 2010 20:36:29 +0000", - "status": "completed", - "subresource_uris": { - "notifications": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json", - "recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json" - }, - "to": "+14158675309", - "to_formatted": "(415) 867-5309", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/test_conference.py b/tests/integration/api/v2010/account/test_conference.py deleted file mode 100644 index 90e013562f..0000000000 --- a/tests/integration/api/v2010/account/test_conference.py +++ /dev/null @@ -1,167 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ConferenceTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences(sid="CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Conferences/CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2008-08-01", - "date_created": "Fri, 18 Feb 2011 19:26:50 +0000", - "date_updated": "Fri, 18 Feb 2011 19:27:33 +0000", - "friendly_name": "AHH YEAH", - "sid": "CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "region": "us1", - "status": "completed", - "subresource_uris": { - "participants": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants.json", - "recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences(sid="CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Conferences.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "conferences": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "date_created": "Mon, 22 Aug 2011 20:58:45 +0000", - "date_updated": "Mon, 22 Aug 2011 20:58:46 +0000", - "friendly_name": null, - "region": "us1", - "sid": "CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "in-progress", - "subresource_uris": { - "participants": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants.json", - "recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences.json?PageSize=1&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "conferences": [], - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences.json?PageSize=1&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences(sid="CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Conferences/CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_update_end_conference_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "date_created": "Mon, 22 Aug 2011 20:58:45 +0000", - "date_updated": "Mon, 22 Aug 2011 20:58:46 +0000", - "friendly_name": null, - "region": "us1", - "sid": "CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "completed", - "subresource_uris": { - "participants": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants.json", - "recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences(sid="CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/test_connect_app.py b/tests/integration/api/v2010/account/test_connect_app.py deleted file mode 100644 index f87058f0cc..0000000000 --- a/tests/integration/api/v2010/account/test_connect_app.py +++ /dev/null @@ -1,167 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ConnectAppTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .connect_apps(sid="CNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ConnectApps/CNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "authorize_redirect_url": "http://example.com/redirect", - "company_name": "Twilio", - "deauthorize_callback_method": "GET", - "deauthorize_callback_url": "http://example.com/deauth", - "description": null, - "friendly_name": "Connect app for deletion", - "homepage_url": "http://example.com/home", - "permissions": [], - "sid": "CNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ConnectApps/CNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .connect_apps(sid="CNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .connect_apps(sid="CNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ConnectApps/CNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "authorize_redirect_url": "http://example.com/redirect", - "company_name": "Twilio", - "deauthorize_callback_method": "GET", - "deauthorize_callback_url": "http://example.com/deauth", - "description": null, - "friendly_name": "Connect app for deletion", - "homepage_url": "http://example.com/home", - "permissions": [], - "sid": "CNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ConnectApps/CNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .connect_apps(sid="CNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .connect_apps.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ConnectApps.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "connect_apps": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "authorize_redirect_url": "http://example.com/redirect", - "company_name": "Twilio", - "deauthorize_callback_method": "GET", - "deauthorize_callback_url": "http://example.com/deauth", - "description": null, - "friendly_name": "Connect app for deletion", - "homepage_url": "http://example.com/home", - "permissions": [], - "sid": "CNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ConnectApps/CNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ConnectApps.json?Page=0&PageSize=50", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ConnectApps.json?Page=0&PageSize=50", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ConnectApps.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .connect_apps.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "connect_apps": [], - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ConnectApps.json?Page=0&PageSize=50", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ConnectApps.json?Page=0&PageSize=50", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ConnectApps.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .connect_apps.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/test_incoming_phone_number.py b/tests/integration/api/v2010/account/test_incoming_phone_number.py deleted file mode 100644 index aaab47a0e9..0000000000 --- a/tests/integration/api/v2010/account/test_incoming_phone_number.py +++ /dev/null @@ -1,319 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class IncomingPhoneNumberTestCase(IntegrationTestCase): - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IncomingPhoneNumbers/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "address_requirements": "none", - "address_sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "beta": false, - "capabilities": { - "mms": true, - "sms": false, - "voice": true - }, - "date_created": "Thu, 30 Jul 2015 23:19:04 +0000", - "date_updated": "Thu, 30 Jul 2015 23:19:04 +0000", - "emergency_status": "Inactive", - "emergency_address_sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "(808) 925-5327", - "identity_sid": "RIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "origin": "origin", - "phone_number": "+18089255327", - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sms_application_sid": "", - "sms_fallback_method": "POST", - "sms_fallback_url": "", - "sms_method": "POST", - "sms_url": "", - "status_callback": "", - "status_callback_method": "POST", - "trunk_sid": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "voice_application_sid": "", - "voice_caller_id_lookup": false, - "voice_fallback_method": "POST", - "voice_fallback_url": null, - "voice_method": "POST", - "voice_url": null - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IncomingPhoneNumbers/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "address_requirements": "none", - "address_sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "beta": false, - "capabilities": { - "mms": true, - "sms": false, - "voice": true - }, - "date_created": "Thu, 30 Jul 2015 23:19:04 +0000", - "date_updated": "Thu, 30 Jul 2015 23:19:04 +0000", - "emergency_status": "Active", - "emergency_address_sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "(808) 925-5327", - "identity_sid": "RIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "origin": "origin", - "phone_number": "+18089255327", - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sms_application_sid": "", - "sms_fallback_method": "POST", - "sms_fallback_url": "", - "sms_method": "POST", - "sms_url": "", - "status_callback": "", - "status_callback_method": "POST", - "trunk_sid": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "voice_application_sid": "", - "voice_caller_id_lookup": false, - "voice_fallback_method": "POST", - "voice_fallback_url": null, - "voice_method": "POST", - "voice_url": null - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IncomingPhoneNumbers/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IncomingPhoneNumbers.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1&Page=0", - "incoming_phone_numbers": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "address_requirements": "none", - "address_sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "beta": null, - "capabilities": { - "mms": true, - "sms": false, - "voice": true - }, - "date_created": "Thu, 30 Jul 2015 23:19:04 +0000", - "date_updated": "Thu, 30 Jul 2015 23:19:04 +0000", - "emergency_status": "Active", - "emergency_address_sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "(808) 925-5327", - "identity_sid": "RIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "origin": "origin", - "phone_number": "+18089255327", - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sms_application_sid": "", - "sms_fallback_method": "POST", - "sms_fallback_url": "", - "sms_method": "POST", - "sms_url": "", - "status_callback": "", - "status_callback_method": "POST", - "trunk_sid": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "voice_application_sid": "", - "voice_caller_id_lookup": false, - "voice_fallback_method": "POST", - "voice_fallback_url": null, - "voice_method": "POST", - "voice_url": null - } - ], - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1&Page=2", - "next_page_uri": null, - "num_pages": 3, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 3, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1&Page=0", - "incoming_phone_numbers": [], - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1&Page=2", - "next_page_uri": null, - "num_pages": 3, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 3, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IncomingPhoneNumbers.json', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "address_requirements": "none", - "address_sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "beta": false, - "capabilities": { - "mms": true, - "sms": false, - "voice": true - }, - "date_created": "Thu, 30 Jul 2015 23:19:04 +0000", - "date_updated": "Thu, 30 Jul 2015 23:19:04 +0000", - "emergency_status": "Active", - "emergency_address_sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "(808) 925-5327", - "identity_sid": "RIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "origin": "origin", - "phone_number": "+18089255327", - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sms_application_sid": "", - "sms_fallback_method": "POST", - "sms_fallback_url": "", - "sms_method": "POST", - "sms_url": "", - "status_callback": "", - "status_callback_method": "POST", - "trunk_sid": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "voice_application_sid": "", - "voice_caller_id_lookup": false, - "voice_fallback_method": "POST", - "voice_fallback_url": null, - "voice_method": "POST", - "voice_url": null - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers.create() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/test_key.py b/tests/integration/api/v2010/account/test_key.py deleted file mode 100644 index 5692b58612..0000000000 --- a/tests/integration/api/v2010/account/test_key.py +++ /dev/null @@ -1,163 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class KeyTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys(sid="SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Keys/SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "SKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "foo", - "date_created": "Mon, 13 Jun 2016 22:50:08 +0000", - "date_updated": "Mon, 13 Jun 2016 22:50:08 +0000" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys(sid="SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys(sid="SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Keys/SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "SKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "foo", - "date_created": "Mon, 13 Jun 2016 22:50:08 +0000", - "date_updated": "Mon, 13 Jun 2016 22:50:08 +0000" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys(sid="SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys(sid="SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Keys/SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys(sid="SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Keys.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "keys": [ - { - "sid": "SKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "foo", - "date_created": "Mon, 13 Jun 2016 22:50:08 +0000", - "date_updated": "Mon, 13 Jun 2016 22:50:08 +0000" - } - ], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Keys.json?PageSize=50&Page=0", - "end": 0, - "previous_page_uri": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Keys.json?PageSize=50&Page=0", - "page_size": 50, - "start": 0, - "next_page_uri": null, - "page": 0 - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "keys": [], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Keys.json?PageSize=50&Page=0", - "end": 0, - "previous_page_uri": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Keys.json?PageSize=50&Page=0", - "page_size": 50, - "start": 0, - "next_page_uri": null, - "page": 0 - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/test_message.py b/tests/integration/api/v2010/account/test_message.py deleted file mode 100644 index bf6bbd42a0..0000000000 --- a/tests/integration/api/v2010/account/test_message.py +++ /dev/null @@ -1,277 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class MessageTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.create(to="+15558675310") - - values = {'To': "+15558675310", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages.json', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "body": "O Slash: \u00d8, PoP: \ud83d\udca9", - "date_created": "Thu, 30 Jul 2015 20:12:31 +0000", - "date_sent": "Thu, 30 Jul 2015 20:12:33 +0000", - "date_updated": "Thu, 30 Jul 2015 20:12:33 +0000", - "direction": "outbound-api", - "error_code": null, - "error_message": null, - "from": "+14155552345", - "messaging_service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "num_media": "0", - "num_segments": "1", - "price": "-0.00750", - "price_unit": "USD", - "sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "sent", - "subresource_uris": { - "media": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media.json" - }, - "to": "+14155552345", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.create(to="+15558675310") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "body": "O Slash: \u00d8, PoP: \ud83d\udca9", - "date_created": "Thu, 30 Jul 2015 20:12:31 +0000", - "date_sent": "Thu, 30 Jul 2015 20:12:33 +0000", - "date_updated": "Thu, 30 Jul 2015 20:12:33 +0000", - "direction": "outbound-api", - "error_code": null, - "error_message": null, - "from": "+14155552345", - "messaging_service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "num_media": "0", - "num_segments": "1", - "price": "-0.00750", - "price_unit": "USD", - "sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "sent", - "subresource_uris": { - "media": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media.json" - }, - "to": "+14155552345", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages.json?PageSize=1&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages.json?PageSize=1&Page=119771", - "messages": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "body": "O Slash: \u00d8, PoP: \ud83d\udca9", - "date_created": "Fri, 04 Sep 2015 22:54:39 +0000", - "date_sent": "Fri, 04 Sep 2015 22:54:41 +0000", - "date_updated": "Fri, 04 Sep 2015 22:54:41 +0000", - "direction": "outbound-api", - "error_code": null, - "error_message": null, - "from": "+14155552345", - "messaging_service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "num_media": "0", - "num_segments": "1", - "price": "-0.00750", - "price_unit": "USD", - "sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "sent", - "subresource_uris": { - "media": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media.json" - }, - "to": "+14155552345", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "next_page_uri": null, - "num_pages": 119772, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 119772, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages.json?PageSize=1&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages.json?PageSize=1&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages.json?PageSize=1&Page=119771", - "messages": [], - "next_page_uri": null, - "num_pages": 119772, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 119772, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages.json?PageSize=1&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(body="body") - - values = {'Body': "body", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "body": "O Slash: \u00d8, PoP: \ud83d\udca9", - "date_created": "Thu, 30 Jul 2015 20:12:31 +0000", - "date_sent": "Thu, 30 Jul 2015 20:12:33 +0000", - "date_updated": "Thu, 30 Jul 2015 20:12:33 +0000", - "direction": "outbound-api", - "error_code": null, - "error_message": null, - "from": "+14155552345", - "messaging_service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "num_media": "0", - "num_segments": "1", - "price": "-0.00750", - "price_unit": "USD", - "sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "sent", - "subresource_uris": { - "media": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media.json" - }, - "to": "+14155552345", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(body="body") - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/test_new_key.py b/tests/integration/api/v2010/account/test_new_key.py deleted file mode 100644 index dccaf54888..0000000000 --- a/tests/integration/api/v2010/account/test_new_key.py +++ /dev/null @@ -1,46 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class NewKeyTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .new_keys.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Keys.json', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "SKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "foo", - "date_created": "Mon, 13 Jun 2016 22:50:08 +0000", - "date_updated": "Mon, 13 Jun 2016 22:50:08 +0000", - "secret": "foobar" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .new_keys.create() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/test_new_signing_key.py b/tests/integration/api/v2010/account/test_new_signing_key.py deleted file mode 100644 index da2952efc4..0000000000 --- a/tests/integration/api/v2010/account/test_new_signing_key.py +++ /dev/null @@ -1,46 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class NewSigningKeyTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .new_signing_keys.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SigningKeys.json', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "SKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "foo", - "date_created": "Mon, 13 Jun 2016 22:50:08 +0000", - "date_updated": "Mon, 13 Jun 2016 22:50:08 +0000", - "secret": "foobar" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .new_signing_keys.create() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/test_notification.py b/tests/integration/api/v2010/account/test_notification.py deleted file mode 100644 index 31451c5a8a..0000000000 --- a/tests/integration/api/v2010/account/test_notification.py +++ /dev/null @@ -1,162 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class NotificationTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .notifications(sid="NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Notifications/NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2008-08-01", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Mon, 13 Sep 2010 20:02:01 +0000", - "date_updated": "Mon, 13 Sep 2010 20:02:01 +0000", - "error_code": "11200", - "log": "0", - "message_date": "Mon, 13 Sep 2010 20:02:00 +0000", - "message_text": "EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=500&ErrorCode=11200&url=http%3A%2F%2Fvoiceforms4000.appspot.com%2Ftwiml", - "more_info": "http://www.twilio.com/docs/errors/11200", - "request_method": "get", - "request_url": "https://voiceforms4000.appspot.com/twiml/9436/question/0", - "request_variables": "AccountSid=ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&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=CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&CalledState=CA&From=%2B17378742833", - "response_body": "blah blah", - "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", - "sid": "NOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications/NOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .notifications(sid="NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .notifications(sid="NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Notifications/NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .notifications(sid="NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .notifications.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Notifications.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json?PageSize=1&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json?PageSize=1&Page=100", - "next_page_uri": null, - "notifications": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2008-08-01", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Thu, 30 Apr 2015 16:47:33 +0000", - "date_updated": "Thu, 30 Apr 2015 16:47:35 +0000", - "error_code": "21609", - "log": "1", - "message_date": "Thu, 30 Apr 2015 16:47:32 +0000", - "message_text": "LogLevel=WARN&invalidStatusCallbackUrl=&Msg=Invalid+Url+for+callSid%3A+CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa+invalid+statusCallbackUrl%3A+&ErrorCode=21609", - "more_info": "https://www.twilio.com/docs/errors/21609", - "request_method": null, - "request_url": "", - "sid": "NOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications/NOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "num_pages": 101, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 101, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json?PageSize=1&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .notifications.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json?PageSize=1&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json?PageSize=1&Page=100", - "next_page_uri": null, - "notifications": [], - "num_pages": 101, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 101, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json?PageSize=1&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .notifications.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/test_outgoing_caller_id.py b/tests/integration/api/v2010/account/test_outgoing_caller_id.py deleted file mode 100644 index cd23276489..0000000000 --- a/tests/integration/api/v2010/account/test_outgoing_caller_id.py +++ /dev/null @@ -1,178 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class OutgoingCallerIdTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .outgoing_caller_ids(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/OutgoingCallerIds/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Fri, 21 Aug 2009 00:11:24 +0000", - "date_updated": "Fri, 21 Aug 2009 00:11:24 +0000", - "friendly_name": "(415) 867-5309", - "phone_number": "+141586753096", - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OutgoingCallerIds/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .outgoing_caller_ids(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .outgoing_caller_ids(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/OutgoingCallerIds/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Fri, 21 Aug 2009 00:11:24 +0000", - "date_updated": "Fri, 21 Aug 2009 00:11:24 +0000", - "friendly_name": "(415) 867-5309", - "phone_number": "+141586753096", - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OutgoingCallerIds/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .outgoing_caller_ids(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .outgoing_caller_ids(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/OutgoingCallerIds/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .outgoing_caller_ids(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .outgoing_caller_ids.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/OutgoingCallerIds.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OutgoingCallerIds.json?Page=0&PageSize=50", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OutgoingCallerIds.json?Page=0&PageSize=50", - "next_page_uri": null, - "num_pages": 1, - "outgoing_caller_ids": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Fri, 21 Aug 2009 00:11:24 +0000", - "date_updated": "Fri, 21 Aug 2009 00:11:24 +0000", - "friendly_name": "(415) 867-5309", - "phone_number": "+141586753096", - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OutgoingCallerIds/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OutgoingCallerIds.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .outgoing_caller_ids.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OutgoingCallerIds.json?Page=0&PageSize=50", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OutgoingCallerIds.json?Page=0&PageSize=50", - "next_page_uri": null, - "num_pages": 1, - "outgoing_caller_ids": [], - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OutgoingCallerIds.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .outgoing_caller_ids.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/test_queue.py b/tests/integration/api/v2010/account/test_queue.py deleted file mode 100644 index 504a830a65..0000000000 --- a/tests/integration/api/v2010/account/test_queue.py +++ /dev/null @@ -1,222 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class QueueTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues(sid="QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Queues/QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "average_wait_time": 0, - "current_size": 0, - "date_created": "Tue, 04 Aug 2015 18:39:09 +0000", - "date_updated": "Tue, 04 Aug 2015 18:39:09 +0000", - "friendly_name": "0.361280134646222", - "max_size": 100, - "sid": "QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues/QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues(sid="QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues(sid="QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Queues/QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "average_wait_time": 0, - "current_size": 0, - "date_created": "Tue, 04 Aug 2015 18:39:09 +0000", - "date_updated": "Tue, 04 Aug 2015 18:39:09 +0000", - "friendly_name": "0.361280134646222", - "max_size": 100, - "sid": "QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues/QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues(sid="QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues(sid="QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Queues/QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues(sid="QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Queues.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues.json?PageSize=1&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues.json?PageSize=1&Page=12857", - "next_page_uri": null, - "num_pages": 12858, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "queues": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "average_wait_time": 0, - "current_size": 0, - "date_created": "Tue, 04 Aug 2015 18:39:09 +0000", - "date_updated": "Tue, 04 Aug 2015 18:39:09 +0000", - "friendly_name": "0.361280134646222", - "max_size": 100, - "sid": "QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues/QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "start": 0, - "total": 12858, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues.json?PageSize=1&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues.json?PageSize=1&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues.json?PageSize=1&Page=12857", - "next_page_uri": null, - "num_pages": 12858, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "queues": [], - "start": 0, - "total": 12858, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues.json?PageSize=1&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues.create(friendly_name="friendly_name") - - values = {'FriendlyName': "friendly_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Queues.json', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "average_wait_time": 0, - "current_size": 0, - "date_created": "Tue, 04 Aug 2015 18:39:09 +0000", - "date_updated": "Tue, 04 Aug 2015 18:39:09 +0000", - "friendly_name": "0.361280134646222", - "max_size": 100, - "sid": "QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues/QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues.create(friendly_name="friendly_name") - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/test_recording.py b/tests/integration/api/v2010/account/test_recording.py deleted file mode 100644 index 8d6683daff..0000000000 --- a/tests/integration/api/v2010/account/test_recording.py +++ /dev/null @@ -1,177 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class RecordingTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings/REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conference_sid": "CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channels": 1, - "date_created": "Fri, 14 Oct 2016 21:56:34 +0000", - "date_updated": "Fri, 14 Oct 2016 21:56:38 +0000", - "start_time": "Fri, 14 Oct 2016 21:56:34 +0000", - "end_time": "Fri, 14 Oct 2016 21:56:38 +0000", - "price": "-0.00250", - "price_unit": "USD", - "duration": "4", - "sid": "REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "source": "StartConferenceRecordingAPI", - "status": "completed", - "error_code": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "subresource_uris": { - "add_on_results": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AddOnResults.json", - "transcriptions": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json" - }, - "encryption_details": { - "encryption_public_key_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "encryption_cek": "OV4h6zrsxMIW7h0Zfqwfn6TI2GCNl54KALlg8wn8YB8KYZhXt6HlgvBWAmQTlfYVeLWydMiCewY0YkDDT1xmNe5huEo9vjuKBS5OmYK4CZkSx1NVv3XOGrZHpd2Pl/5WJHVhUK//AUO87uh5qnUP2E0KoLh1nyCLeGcEkXU0RfpPn/6nxjof/n6m6OzZOyeIRK4Oed5+rEtjqFDfqT0EVKjs6JAxv+f0DCc1xYRHl2yV8bahUPVKs+bHYdy4PVszFKa76M/Uae4jFA9Lv233JqWcxj+K2UoghuGhAFbV/JQIIswY2CBYI8JlVSifSqNEl9vvsTJ8bkVMm3MKbG2P7Q==", - "encryption_iv": "8I2hhNIYNTrwxfHk" - } - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings/REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json?PageSize=1&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "recordings": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conference_sid": "CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channels": 1, - "date_created": "Fri, 14 Oct 2016 21:56:34 +0000", - "date_updated": "Fri, 14 Oct 2016 21:56:38 +0000", - "start_time": "Fri, 14 Oct 2016 21:56:34 +0000", - "end_time": "Fri, 14 Oct 2016 21:56:38 +0000", - "price": "0.04", - "price_unit": "USD", - "duration": "4", - "sid": "REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "source": "StartConferenceRecordingAPI", - "status": "completed", - "error_code": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "subresource_uris": { - "add_on_results": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AddOnResults.json", - "transcriptions": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json" - }, - "encryption_details": { - "encryption_public_key_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "encryption_cek": "OV4h6zrsxMIW7h0Zfqwfn6TI2GCNl54KALlg8wn8YB8KYZhXt6HlgvBWAmQTlfYVeLWydMiCewY0YkDDT1xmNe5huEo9vjuKBS5OmYK4CZkSx1NVv3XOGrZHpd2Pl/5WJHVhUK//AUO87uh5qnUP2E0KoLh1nyCLeGcEkXU0RfpPn/6nxjof/n6m6OzZOyeIRK4Oed5+rEtjqFDfqT0EVKjs6JAxv+f0DCc1xYRHl2yV8bahUPVKs+bHYdy4PVszFKa76M/Uae4jFA9Lv233JqWcxj+K2UoghuGhAFbV/JQIIswY2CBYI8JlVSifSqNEl9vvsTJ8bkVMm3MKbG2P7Q==", - "encryption_iv": "8I2hhNIYNTrwxfHk" - } - } - ], - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json?PageSize=1&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json?PageSize=1&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "recordings": [], - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json?PageSize=1&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/test_short_code.py b/tests/integration/api/v2010/account/test_short_code.py deleted file mode 100644 index 632569b2dd..0000000000 --- a/tests/integration/api/v2010/account/test_short_code.py +++ /dev/null @@ -1,170 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ShortCodeTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes(sid="SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SMS/ShortCodes/SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "date_created": null, - "date_updated": null, - "friendly_name": "API_CLUSTER_TEST_SHORT_CODE", - "short_code": "99990", - "sid": "SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sms_fallback_method": "POST", - "sms_fallback_url": null, - "sms_method": "POST", - "sms_url": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SMS/ShortCodes/SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes(sid="SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes(sid="SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SMS/ShortCodes/SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "date_created": null, - "date_updated": null, - "friendly_name": "API_CLUSTER_TEST_SHORT_CODE", - "short_code": "99990", - "sid": "SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sms_fallback_method": "POST", - "sms_fallback_url": null, - "sms_method": "POST", - "sms_url": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SMS/ShortCodes/SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes(sid="SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SMS/ShortCodes.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SMS/ShortCodes.json?Page=0&PageSize=50", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SMS/ShortCodes.json?Page=0&PageSize=50", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "short_codes": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "date_created": null, - "date_updated": null, - "friendly_name": "API_CLUSTER_TEST_SHORT_CODE", - "short_code": "99990", - "sid": "SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sms_fallback_method": "POST", - "sms_fallback_url": null, - "sms_method": "POST", - "sms_url": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SMS/ShortCodes/SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SMS/ShortCodes.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SMS/ShortCodes.json?Page=0&PageSize=50", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SMS/ShortCodes.json?Page=0&PageSize=50", - "next_page_uri": null, - "num_pages": 1, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "short_codes": [], - "start": 0, - "total": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SMS/ShortCodes.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/test_signing_key.py b/tests/integration/api/v2010/account/test_signing_key.py deleted file mode 100644 index 4e42b98cb3..0000000000 --- a/tests/integration/api/v2010/account/test_signing_key.py +++ /dev/null @@ -1,163 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class SigningKeyTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .signing_keys(sid="SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SigningKeys/SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "SKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "foo", - "date_created": "Mon, 13 Jun 2016 22:50:08 +0000", - "date_updated": "Mon, 13 Jun 2016 22:50:08 +0000" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .signing_keys(sid="SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .signing_keys(sid="SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SigningKeys/SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "SKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "foo", - "date_created": "Mon, 13 Jun 2016 22:50:08 +0000", - "date_updated": "Mon, 13 Jun 2016 22:50:08 +0000" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .signing_keys(sid="SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .signing_keys(sid="SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SigningKeys/SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .signing_keys(sid="SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .signing_keys.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SigningKeys.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "signing_keys": [ - { - "sid": "SKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "foo", - "date_created": "Mon, 13 Jun 2016 22:50:08 +0000", - "date_updated": "Mon, 13 Jun 2016 22:50:08 +0000" - } - ], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SigningKeys.json?PageSize=50&Page=0", - "end": 0, - "previous_page_uri": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SigningKeys.json?PageSize=50&Page=0", - "page_size": 50, - "start": 0, - "next_page_uri": null, - "page": 0 - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .signing_keys.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "signing_keys": [], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SigningKeys.json?PageSize=50&Page=0", - "end": 0, - "previous_page_uri": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SigningKeys.json?PageSize=50&Page=0", - "page_size": 50, - "start": 0, - "next_page_uri": null, - "page": 0 - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .signing_keys.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/test_sip.py b/tests/integration/api/v2010/account/test_sip.py deleted file mode 100644 index abff10a9fd..0000000000 --- a/tests/integration/api/v2010/account/test_sip.py +++ /dev/null @@ -1,16 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class SipTestCase(IntegrationTestCase): - pass diff --git a/tests/integration/api/v2010/account/test_token.py b/tests/integration/api/v2010/account/test_token.py deleted file mode 100644 index ed133441a5..0000000000 --- a/tests/integration/api/v2010/account/test_token.py +++ /dev/null @@ -1,57 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class TokenTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tokens.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tokens.json', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Fri, 24 Jul 2015 18:43:58 +0000", - "date_updated": "Fri, 24 Jul 2015 18:43:58 +0000", - "ice_servers": [ - { - "url": "stun:global.stun:3478?transport=udp" - }, - { - "credential": "5SR2x8mZK1lTFJW3NVgLGw6UM9C0dja4jI/Hdw3xr+w=", - "url": "turn:global.turn:3478?transport=udp", - "username": "cda92e5006c7810494639fc466ecc80182cef8183fdf400f84c4126f3b59d0bb" - } - ], - "password": "5SR2x8mZK1lTFJW3NVgLGw6UM9C0dja4jI/Hdw3xr+w=", - "ttl": "86400", - "username": "cda92e5006c7810494639fc466ecc80182cef8183fdf400f84c4126f3b59d0bb" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tokens.create() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/test_transcription.py b/tests/integration/api/v2010/account/test_transcription.py deleted file mode 100644 index 7861454743..0000000000 --- a/tests/integration/api/v2010/account/test_transcription.py +++ /dev/null @@ -1,157 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class TranscriptionTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .transcriptions(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Transcriptions/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2008-08-01", - "date_created": "Sun, 13 Feb 2011 02:12:08 +0000", - "date_updated": "Sun, 13 Feb 2011 02:30:01 +0000", - "duration": "1", - "price": "-0.05000", - "price_unit": "USD", - "recording_sid": "REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "failed", - "transcription_text": "(blank)", - "type": "fast", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .transcriptions(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .transcriptions(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Transcriptions/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .transcriptions(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .transcriptions.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Transcriptions.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json?PageSize=1&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json?PageSize=1&Page=3", - "next_page_uri": null, - "num_pages": 4, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 4, - "transcriptions": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2008-08-01", - "date_created": "Thu, 25 Aug 2011 20:59:45 +0000", - "date_updated": "Thu, 25 Aug 2011 20:59:45 +0000", - "duration": "10", - "price": "0.00000", - "price_unit": "USD", - "recording_sid": "REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "completed", - "transcription_text": null, - "type": "fast", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json?PageSize=1&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .transcriptions.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json?PageSize=1&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json?PageSize=1&Page=3", - "next_page_uri": null, - "num_pages": 4, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 4, - "transcriptions": [], - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json?PageSize=1&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .transcriptions.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/test_usage.py b/tests/integration/api/v2010/account/test_usage.py deleted file mode 100644 index 6227c0af14..0000000000 --- a/tests/integration/api/v2010/account/test_usage.py +++ /dev/null @@ -1,16 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class UsageTestCase(IntegrationTestCase): - pass diff --git a/tests/integration/api/v2010/account/test_validation_request.py b/tests/integration/api/v2010/account/test_validation_request.py deleted file mode 100644 index b21b08338e..0000000000 --- a/tests/integration/api/v2010/account/test_validation_request.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ValidationRequestTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .validation_requests.create(phone_number="+15017122661") - - values = {'PhoneNumber': "+15017122661", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/OutgoingCallerIds.json', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "phone_number": "+18001234567", - "validation_code": 100 - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .validation_requests.create(phone_number="+15017122661") - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/usage/__init__.py b/tests/integration/api/v2010/account/usage/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/api/v2010/account/usage/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/api/v2010/account/usage/record/__init__.py b/tests/integration/api/v2010/account/usage/record/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/api/v2010/account/usage/record/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/api/v2010/account/usage/record/test_all_time.py b/tests/integration/api/v2010/account/usage/record/test_all_time.py deleted file mode 100644 index 4ac9769d06..0000000000 --- a/tests/integration/api/v2010/account/usage/record/test_all_time.py +++ /dev/null @@ -1,111 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class AllTimeTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records \ - .all_time.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Usage/Records/AllTime.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/AllTime?Page=0&PageSize=1", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/AllTime?Page=68&PageSize=1", - "next_page_uri": null, - "num_pages": 69, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 69, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/AllTime", - "usage_records": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "category": "sms-inbound-shortcode", - "count": "0", - "count_unit": "messages", - "description": "Short Code Inbound SMS", - "end_date": "2015-09-04", - "price": "0", - "price_unit": "usd", - "start_date": "2011-08-23", - "subresource_uris": { - "all_time": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/AllTime.json?Category=sms-inbound-shortcode", - "daily": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Daily.json?Category=sms-inbound-shortcode", - "last_month": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/LastMonth.json?Category=sms-inbound-shortcode", - "monthly": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Monthly.json?Category=sms-inbound-shortcode", - "this_month": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/ThisMonth.json?Category=sms-inbound-shortcode", - "today": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Today.json?Category=sms-inbound-shortcode", - "yearly": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yearly.json?Category=sms-inbound-shortcode", - "yesterday": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yesterday.json?Category=sms-inbound-shortcode" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/AllTime?Category=sms-inbound-shortcode&StartDate=2011-08-23&EndDate=2015-09-04", - "usage": "0", - "usage_unit": "messages" - } - ] - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records \ - .all_time.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/AllTime?Page=0&PageSize=1", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/AllTime?Page=68&PageSize=1", - "next_page_uri": null, - "num_pages": 69, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 69, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/AllTime", - "usage_records": [] - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records \ - .all_time.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/usage/record/test_daily.py b/tests/integration/api/v2010/account/usage/record/test_daily.py deleted file mode 100644 index 013375287d..0000000000 --- a/tests/integration/api/v2010/account/usage/record/test_daily.py +++ /dev/null @@ -1,111 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class DailyTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records \ - .daily.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Usage/Records/Daily.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Daily?Page=0&PageSize=1", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Daily?Page=101843&PageSize=1", - "next_page_uri": null, - "num_pages": 101844, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 101844, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Daily", - "usage_records": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "category": "sms-inbound-shortcode", - "count": "0", - "count_unit": "messages", - "description": "Short Code Inbound SMS", - "end_date": "2015-09-06", - "price": "0", - "price_unit": "usd", - "start_date": "2015-09-06", - "subresource_uris": { - "all_time": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/AllTime.json?Category=sms-inbound-shortcode", - "daily": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Daily.json?Category=sms-inbound-shortcode", - "last_month": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/LastMonth.json?Category=sms-inbound-shortcode", - "monthly": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Monthly.json?Category=sms-inbound-shortcode", - "this_month": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/ThisMonth.json?Category=sms-inbound-shortcode", - "today": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Today.json?Category=sms-inbound-shortcode", - "yearly": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yearly.json?Category=sms-inbound-shortcode", - "yesterday": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yesterday.json?Category=sms-inbound-shortcode" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Daily?Category=sms-inbound-shortcode&StartDate=2015-09-06&EndDate=2015-09-06", - "usage": "0", - "usage_unit": "messages" - } - ] - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records \ - .daily.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Daily?Page=0&PageSize=1", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Daily?Page=101843&PageSize=1", - "next_page_uri": null, - "num_pages": 101844, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 101844, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Daily", - "usage_records": [] - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records \ - .daily.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/usage/record/test_last_month.py b/tests/integration/api/v2010/account/usage/record/test_last_month.py deleted file mode 100644 index 62366b8769..0000000000 --- a/tests/integration/api/v2010/account/usage/record/test_last_month.py +++ /dev/null @@ -1,111 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class LastMonthTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records \ - .last_month.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Usage/Records/LastMonth.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/LastMonth?Page=0&PageSize=1", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/LastMonth?Page=68&PageSize=1", - "next_page_uri": null, - "num_pages": 69, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 69, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/LastMonth", - "usage_records": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "category": "sms-inbound-shortcode", - "count": "0", - "count_unit": "messages", - "description": "Short Code Inbound SMS", - "end_date": "2015-08-31", - "price": "0", - "price_unit": "usd", - "start_date": "2015-08-01", - "subresource_uris": { - "all_time": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/AllTime.json?Category=sms-inbound-shortcode", - "daily": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Daily.json?Category=sms-inbound-shortcode", - "last_month": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/LastMonth.json?Category=sms-inbound-shortcode", - "monthly": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Monthly.json?Category=sms-inbound-shortcode", - "this_month": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/ThisMonth.json?Category=sms-inbound-shortcode", - "today": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Today.json?Category=sms-inbound-shortcode", - "yearly": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yearly.json?Category=sms-inbound-shortcode", - "yesterday": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yesterday.json?Category=sms-inbound-shortcode" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/LastMonth?Category=sms-inbound-shortcode&StartDate=2015-08-01&EndDate=2015-08-31", - "usage": "0", - "usage_unit": "messages" - } - ] - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records \ - .last_month.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/LastMonth?Page=0&PageSize=1", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/LastMonth?Page=68&PageSize=1", - "next_page_uri": null, - "num_pages": 69, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 69, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/LastMonth", - "usage_records": [] - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records \ - .last_month.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/usage/record/test_monthly.py b/tests/integration/api/v2010/account/usage/record/test_monthly.py deleted file mode 100644 index 4e2ad69ddf..0000000000 --- a/tests/integration/api/v2010/account/usage/record/test_monthly.py +++ /dev/null @@ -1,111 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class MonthlyTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records \ - .monthly.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Usage/Records/Monthly.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Monthly?Page=0&PageSize=1", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Monthly?Page=3449&PageSize=1", - "next_page_uri": null, - "num_pages": 3450, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 3450, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Monthly", - "usage_records": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "category": "sms-inbound-shortcode", - "count": "0", - "count_unit": "messages", - "description": "Short Code Inbound SMS", - "end_date": "2015-09-04", - "price": "0", - "price_unit": "usd", - "start_date": "2015-09-01", - "subresource_uris": { - "all_time": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/AllTime.json?Category=sms-inbound-shortcode", - "daily": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Daily.json?Category=sms-inbound-shortcode", - "last_month": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/LastMonth.json?Category=sms-inbound-shortcode", - "monthly": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Monthly.json?Category=sms-inbound-shortcode", - "this_month": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/ThisMonth.json?Category=sms-inbound-shortcode", - "today": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Today.json?Category=sms-inbound-shortcode", - "yearly": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yearly.json?Category=sms-inbound-shortcode", - "yesterday": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yesterday.json?Category=sms-inbound-shortcode" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Monthly?Category=sms-inbound-shortcode&StartDate=2015-09-01&EndDate=2015-09-04", - "usage": "0", - "usage_unit": "messages" - } - ] - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records \ - .monthly.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Monthly?Page=0&PageSize=1", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Monthly?Page=3449&PageSize=1", - "next_page_uri": null, - "num_pages": 3450, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 3450, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Monthly", - "usage_records": [] - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records \ - .monthly.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/usage/record/test_this_month.py b/tests/integration/api/v2010/account/usage/record/test_this_month.py deleted file mode 100644 index 3ce574c01a..0000000000 --- a/tests/integration/api/v2010/account/usage/record/test_this_month.py +++ /dev/null @@ -1,111 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ThisMonthTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records \ - .this_month.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Usage/Records/ThisMonth.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/ThisMonth?Page=0&PageSize=1", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/ThisMonth?Page=68&PageSize=1", - "next_page_uri": null, - "num_pages": 69, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 69, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/ThisMonth", - "usage_records": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "category": "sms-inbound-shortcode", - "count": "0", - "count_unit": "messages", - "description": "Short Code Inbound SMS", - "end_date": "2015-09-04", - "price": "0", - "price_unit": "usd", - "start_date": "2015-09-01", - "subresource_uris": { - "all_time": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/AllTime.json?Category=sms-inbound-shortcode", - "daily": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Daily.json?Category=sms-inbound-shortcode", - "last_month": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/LastMonth.json?Category=sms-inbound-shortcode", - "monthly": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Monthly.json?Category=sms-inbound-shortcode", - "this_month": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/ThisMonth.json?Category=sms-inbound-shortcode", - "today": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Today.json?Category=sms-inbound-shortcode", - "yearly": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yearly.json?Category=sms-inbound-shortcode", - "yesterday": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yesterday.json?Category=sms-inbound-shortcode" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/ThisMonth?Category=sms-inbound-shortcode&StartDate=2015-09-01&EndDate=2015-09-04", - "usage": "0", - "usage_unit": "messages" - } - ] - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records \ - .this_month.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/ThisMonth?Page=0&PageSize=1", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/ThisMonth?Page=68&PageSize=1", - "next_page_uri": null, - "num_pages": 69, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 69, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/ThisMonth", - "usage_records": [] - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records \ - .this_month.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/usage/record/test_today.py b/tests/integration/api/v2010/account/usage/record/test_today.py deleted file mode 100644 index 229ed60b08..0000000000 --- a/tests/integration/api/v2010/account/usage/record/test_today.py +++ /dev/null @@ -1,111 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class TodayTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records \ - .today.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Usage/Records/Today.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Today?Page=0&PageSize=1", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Today?Page=68&PageSize=1", - "next_page_uri": null, - "num_pages": 69, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 69, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Today", - "usage_records": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "category": "sms-inbound-shortcode", - "count": "0", - "count_unit": "messages", - "description": "Short Code Inbound SMS", - "end_date": "2015-09-04", - "price": "0", - "price_unit": "usd", - "start_date": "2015-09-04", - "subresource_uris": { - "all_time": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/AllTime.json?Category=sms-inbound-shortcode", - "daily": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Daily.json?Category=sms-inbound-shortcode", - "last_month": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/LastMonth.json?Category=sms-inbound-shortcode", - "monthly": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Monthly.json?Category=sms-inbound-shortcode", - "this_month": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/ThisMonth.json?Category=sms-inbound-shortcode", - "today": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Today.json?Category=sms-inbound-shortcode", - "yearly": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yearly.json?Category=sms-inbound-shortcode", - "yesterday": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yesterday.json?Category=sms-inbound-shortcode" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Today?Category=sms-inbound-shortcode&StartDate=2015-09-04&EndDate=2015-09-04", - "usage": "0", - "usage_unit": "messages" - } - ] - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records \ - .today.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Today?Page=0&PageSize=1", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Today?Page=68&PageSize=1", - "next_page_uri": null, - "num_pages": 69, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 69, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Today", - "usage_records": [] - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records \ - .today.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/usage/record/test_yearly.py b/tests/integration/api/v2010/account/usage/record/test_yearly.py deleted file mode 100644 index 6805e43085..0000000000 --- a/tests/integration/api/v2010/account/usage/record/test_yearly.py +++ /dev/null @@ -1,111 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class YearlyTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records \ - .yearly.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Usage/Records/Yearly.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yearly?Page=0&PageSize=1", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yearly?Page=344&PageSize=1", - "next_page_uri": null, - "num_pages": 345, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 345, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yearly", - "usage_records": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "category": "sms-inbound-shortcode", - "count": "0", - "count_unit": "messages", - "description": "Short Code Inbound SMS", - "end_date": "2015-09-04", - "price": "0", - "price_unit": "usd", - "start_date": "2015-01-01", - "subresource_uris": { - "all_time": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/AllTime.json?Category=sms-inbound-shortcode", - "daily": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Daily.json?Category=sms-inbound-shortcode", - "last_month": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/LastMonth.json?Category=sms-inbound-shortcode", - "monthly": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Monthly.json?Category=sms-inbound-shortcode", - "this_month": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/ThisMonth.json?Category=sms-inbound-shortcode", - "today": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Today.json?Category=sms-inbound-shortcode", - "yearly": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yearly.json?Category=sms-inbound-shortcode", - "yesterday": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yesterday.json?Category=sms-inbound-shortcode" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yearly?Category=sms-inbound-shortcode&StartDate=2015-01-01&EndDate=2015-09-04", - "usage": "0", - "usage_unit": "messages" - } - ] - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records \ - .yearly.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yearly?Page=0&PageSize=1", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yearly?Page=344&PageSize=1", - "next_page_uri": null, - "num_pages": 345, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 345, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yearly", - "usage_records": [] - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records \ - .yearly.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/usage/record/test_yesterday.py b/tests/integration/api/v2010/account/usage/record/test_yesterday.py deleted file mode 100644 index bde3b734fe..0000000000 --- a/tests/integration/api/v2010/account/usage/record/test_yesterday.py +++ /dev/null @@ -1,111 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class YesterdayTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records \ - .yesterday.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Usage/Records/Yesterday.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yesterday?Page=0&PageSize=1", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yesterday?Page=68&PageSize=1", - "next_page_uri": null, - "num_pages": 69, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 69, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yesterday", - "usage_records": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "category": "sms-inbound-shortcode", - "count": "0", - "count_unit": "messages", - "description": "Short Code Inbound SMS", - "end_date": "2015-09-03", - "price": "0", - "price_unit": "usd", - "start_date": "2015-09-03", - "subresource_uris": { - "all_time": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/AllTime.json?Category=sms-inbound-shortcode", - "daily": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Daily.json?Category=sms-inbound-shortcode", - "last_month": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/LastMonth.json?Category=sms-inbound-shortcode", - "monthly": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Monthly.json?Category=sms-inbound-shortcode", - "this_month": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/ThisMonth.json?Category=sms-inbound-shortcode", - "today": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Today.json?Category=sms-inbound-shortcode", - "yearly": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yearly.json?Category=sms-inbound-shortcode", - "yesterday": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yesterday.json?Category=sms-inbound-shortcode" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yesterday?Category=sms-inbound-shortcode&StartDate=2015-09-03&EndDate=2015-09-03", - "usage": "0", - "usage_unit": "messages" - } - ] - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records \ - .yesterday.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yesterday?Page=0&PageSize=1", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yesterday?Page=68&PageSize=1", - "next_page_uri": null, - "num_pages": 69, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 69, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yesterday", - "usage_records": [] - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records \ - .yesterday.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/usage/test_record.py b/tests/integration/api/v2010/account/usage/test_record.py deleted file mode 100644 index 2da303ba13..0000000000 --- a/tests/integration/api/v2010/account/usage/test_record.py +++ /dev/null @@ -1,108 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class RecordTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Usage/Records.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records?Page=0&PageSize=1", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records?Page=68&PageSize=1", - "next_page_uri": null, - "num_pages": 69, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 69, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records", - "usage_records": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "category": "totalprice", - "count": null, - "count_unit": "", - "description": "Total Price", - "end_date": "2015-09-04", - "price": "2192.84855", - "price_unit": "usd", - "start_date": "2011-08-23", - "subresource_uris": { - "all_time": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/AllTime.json?Category=totalprice", - "daily": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Daily.json?Category=totalprice", - "last_month": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/LastMonth.json?Category=totalprice", - "monthly": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Monthly.json?Category=totalprice", - "this_month": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/ThisMonth.json?Category=totalprice", - "today": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Today.json?Category=totalprice", - "yearly": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yearly.json?Category=totalprice", - "yesterday": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yesterday.json?Category=totalprice" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records?Category=totalprice&StartDate=2011-08-23&EndDate=2015-09-04", - "usage": "2192.84855", - "usage_unit": "usd" - } - ] - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records?Page=0&PageSize=1", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records?Page=68&PageSize=1", - "next_page_uri": null, - "num_pages": 69, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 69, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records", - "usage_records": [] - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .records.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/usage/test_trigger.py b/tests/integration/api/v2010/account/usage/test_trigger.py deleted file mode 100644 index 834322063b..0000000000 --- a/tests/integration/api/v2010/account/usage/test_trigger.py +++ /dev/null @@ -1,265 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class TriggerTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .triggers(sid="UTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Usage/Triggers/UTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "callback_method": "GET", - "callback_url": "http://cap.com/streetfight", - "current_value": "0", - "date_created": "Sun, 06 Sep 2015 12:58:45 +0000", - "date_fired": null, - "date_updated": "Sun, 06 Sep 2015 12:58:45 +0000", - "friendly_name": "raphael-cluster-1441544325.86", - "recurring": "yearly", - "sid": "UTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "trigger_by": "price", - "trigger_value": "50", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Triggers/UTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "usage_category": "totalprice", - "usage_record_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records?Category=totalprice" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .triggers(sid="UTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .triggers(sid="UTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Usage/Triggers/UTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "callback_method": "GET", - "callback_url": "http://cap.com/streetfight", - "current_value": "0", - "date_created": "Sun, 06 Sep 2015 12:58:45 +0000", - "date_fired": null, - "date_updated": "Sun, 06 Sep 2015 12:58:45 +0000", - "friendly_name": "raphael-cluster-1441544325.86", - "recurring": "yearly", - "sid": "UTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "trigger_by": "price", - "trigger_value": "50", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Triggers/UTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "usage_category": "totalprice", - "usage_record_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records?Category=totalprice" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .triggers(sid="UTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .triggers(sid="UTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Usage/Triggers/UTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .triggers(sid="UTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .triggers.create(callback_url="https://example.com", trigger_value="trigger_value", usage_category="answering-machine-detection") - - values = { - 'CallbackUrl': "https://example.com", - 'TriggerValue': "trigger_value", - 'UsageCategory': "answering-machine-detection", - } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Usage/Triggers.json', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "callback_method": "GET", - "callback_url": "http://cap.com/streetfight", - "current_value": "0", - "date_created": "Sun, 06 Sep 2015 12:58:45 +0000", - "date_fired": null, - "date_updated": "Sun, 06 Sep 2015 12:58:45 +0000", - "friendly_name": "raphael-cluster-1441544325.86", - "recurring": "yearly", - "sid": "UTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "trigger_by": "price", - "trigger_value": "50", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Triggers/UTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "usage_category": "totalprice", - "usage_record_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records?Category=totalprice" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .triggers.create(callback_url="https://example.com", trigger_value="trigger_value", usage_category="answering-machine-detection") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .triggers.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Usage/Triggers.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Triggers?PageSize=1&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Triggers?PageSize=1&Page=626", - "next_page_uri": null, - "num_pages": 627, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 627, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Triggers", - "usage_triggers": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "callback_method": "GET", - "callback_url": "http://cap.com/streetfight", - "current_value": "0", - "date_created": "Sun, 06 Sep 2015 12:58:45 +0000", - "date_fired": null, - "date_updated": "Sun, 06 Sep 2015 12:58:45 +0000", - "friendly_name": "raphael-cluster-1441544325.86", - "recurring": "yearly", - "sid": "UTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "trigger_by": "price", - "trigger_value": "50", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Triggers/UTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "usage_category": "totalprice", - "usage_record_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records?Category=totalprice" - } - ] - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .triggers.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Triggers?PageSize=1&Page=0", - "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Triggers?PageSize=1&Page=626", - "next_page_uri": null, - "num_pages": 627, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "total": 627, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Triggers", - "usage_triggers": [] - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .triggers.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/test_account.py b/tests/integration/api/v2010/test_account.py deleted file mode 100644 index 1f09044922..0000000000 --- a/tests/integration/api/v2010/test_account.py +++ /dev/null @@ -1,255 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class AccountTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts.json', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "auth_token": "auth_token", - "date_created": "Thu, 30 Jul 2015 20:00:00 +0000", - "date_updated": "Thu, 30 Jul 2015 20:00:00 +0000", - "friendly_name": "friendly_name", - "owner_account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "active", - "subresource_uris": { - "available_phone_numbers": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers.json", - "calls": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls.json", - "conferences": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences.json", - "incoming_phone_numbers": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json", - "notifications": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json", - "outgoing_caller_ids": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OutgoingCallerIds.json", - "recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json", - "transcriptions": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json", - "addresses": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Addresses.json", - "signing_keys": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SigningKeys.json", - "connect_apps": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ConnectApps.json", - "sip": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP.json", - "authorized_connect_apps": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AuthorizedConnectApps.json", - "usage": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage.json", - "keys": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Keys.json", - "applications": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Applications.json", - "short_codes": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SMS/ShortCodes.json", - "queues": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues.json", - "messages": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages.json" - }, - "type": "Full", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts.create() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "auth_token": "auth_token", - "date_created": "Thu, 30 Jul 2015 20:00:00 +0000", - "date_updated": "Thu, 30 Jul 2015 20:00:00 +0000", - "friendly_name": "friendly_name", - "owner_account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "active", - "subresource_uris": { - "available_phone_numbers": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers.json", - "calls": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls.json", - "conferences": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences.json", - "incoming_phone_numbers": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json", - "notifications": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json", - "outgoing_caller_ids": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OutgoingCallerIds.json", - "recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json", - "transcriptions": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json", - "addresses": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Addresses.json", - "signing_keys": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SigningKeys.json", - "connect_apps": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ConnectApps.json", - "sip": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP.json", - "authorized_connect_apps": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AuthorizedConnectApps.json", - "usage": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage.json", - "keys": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Keys.json", - "applications": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Applications.json", - "short_codes": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SMS/ShortCodes.json", - "queues": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues.json", - "messages": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages.json" - }, - "type": "Full", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts.json', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "first_page_uri": "/2010-04-01/Accounts.json?PageSize=50&Page=0", - "end": 0, - "previous_page_uri": null, - "accounts": [], - "uri": "/2010-04-01/Accounts.json?PageSize=50&Page=0", - "page_size": 50, - "start": 0, - "next_page_uri": null, - "page": 0 - } - ''' - )) - - actual = self.client.api.v2010.accounts.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "first_page_uri": "/2010-04-01/Accounts.json?PageSize=50&Page=0", - "end": 0, - "previous_page_uri": null, - "accounts": [ - { - "auth_token": "auth_token", - "date_created": "Thu, 30 Jul 2015 20:00:00 +0000", - "date_updated": "Thu, 30 Jul 2015 20:00:00 +0000", - "friendly_name": "friendly_name", - "owner_account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "active", - "subresource_uris": { - "available_phone_numbers": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers.json", - "calls": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls.json", - "conferences": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences.json", - "incoming_phone_numbers": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json", - "notifications": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json", - "outgoing_caller_ids": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OutgoingCallerIds.json", - "recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json", - "transcriptions": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json", - "addresses": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Addresses.json", - "signing_keys": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SigningKeys.json", - "connect_apps": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ConnectApps.json", - "sip": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP.json", - "authorized_connect_apps": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AuthorizedConnectApps.json", - "usage": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage.json", - "keys": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Keys.json", - "applications": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Applications.json", - "short_codes": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SMS/ShortCodes.json", - "queues": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues.json", - "messages": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages.json" - }, - "type": "Full", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "uri": "/2010-04-01/Accounts.json?PageSize=50&Page=0", - "page_size": 50, - "start": 0, - "next_page_uri": null, - "page": 0 - } - ''' - )) - - actual = self.client.api.v2010.accounts.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "auth_token": "AUTHTOKEN", - "date_created": "Sun, 15 Mar 2009 02:08:47 +0000", - "date_updated": "Wed, 25 Aug 2010 01:30:09 +0000", - "friendly_name": "Test Account", - "sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "owner_account_sid": "ACbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - "status": "active", - "subresource_uris": { - "available_phone_numbers": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers.json", - "calls": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls.json", - "conferences": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences.json", - "incoming_phone_numbers": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json", - "notifications": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json", - "outgoing_caller_ids": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OutgoingCallerIds.json", - "recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json", - "sms_messages": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SMS/Messages.json", - "transcriptions": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json" - }, - "type": "Full", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts(sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/chat/__init__.py b/tests/integration/chat/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/chat/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/chat/v1/__init__.py b/tests/integration/chat/v1/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/chat/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/chat/v1/service/__init__.py b/tests/integration/chat/v1/service/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/chat/v1/service/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/chat/v1/service/channel/__init__.py b/tests/integration/chat/v1/service/channel/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/chat/v1/service/channel/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/chat/v1/service/channel/test_invite.py b/tests/integration/chat/v1/service/channel/test_invite.py deleted file mode 100644 index 51dc7309a2..0000000000 --- a/tests/integration/chat/v1/service/channel/test_invite.py +++ /dev/null @@ -1,195 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class InviteTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites(sid="INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Invites/INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "identity": "identity", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites/INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites(sid="INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites.create(identity="identity") - - values = {'Identity': "identity", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Invites', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "identity": "identity", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites/INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites.create(identity="identity") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Invites', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "invites": [], - "meta": { - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0", - "key": "invites", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "invites": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "identity": "identity", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites/INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0", - "key": "invites", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites.list() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites(sid="INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Invites/INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites(sid="INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/chat/v1/service/channel/test_member.py b/tests/integration/chat/v1/service/channel/test_member.py deleted file mode 100644 index 22b64c0527..0000000000 --- a/tests/integration/chat/v1/service/channel/test_member.py +++ /dev/null @@ -1,263 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class MemberTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members/MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "last_consumed_message_index": null, - "last_consumption_timestamp": null, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members.create(identity="identity") - - values = {'Identity': "identity", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "last_consumed_message_index": null, - "last_consumption_timestamp": null, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members.create(identity="identity") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0", - "next_page_url": null, - "key": "members" - }, - "members": [ - { - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "last_consumed_message_index": null, - "last_consumption_timestamp": null, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0", - "next_page_url": null, - "key": "members" - }, - "members": [] - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members.list() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members/MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members/MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_role_sid_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "last_consumed_message_index": null, - "last_consumption_timestamp": null, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_update_last_consumed_message_index_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "last_consumed_message_index": 666, - "last_consumption_timestamp": null, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/chat/v1/service/channel/test_message.py b/tests/integration/chat/v1/service/channel/test_message.py deleted file mode 100644 index b4e7415882..0000000000 --- a/tests/integration/chat/v1/service/channel/test_message.py +++ /dev/null @@ -1,273 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class MessageTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "was_edited": false, - "from": "system", - "attributes": "{}", - "body": "Hello", - "index": 0, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.create(body="body") - - values = {'Body': "body", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "attributes": null, - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "was_edited": false, - "from": "system", - "body": "Hello", - "index": 0, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.create(body="body") - - self.assertIsNotNone(actual) - - def test_create_with_attributes_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "was_edited": false, - "from": "system", - "attributes": "{}", - "body": "Hello", - "index": 0, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.create(body="body") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages?PageSize=50&Page=0", - "next_page_url": null, - "key": "messages" - }, - "messages": [ - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "was_edited": false, - "from": "system", - "attributes": "{}", - "body": "Hello", - "index": 0, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages?PageSize=50&Page=0", - "next_page_url": null, - "key": "messages" - }, - "messages": [] - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.list() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "attributes": "{\\"test\\": \\"test\\"}", - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "was_edited": false, - "from": "system", - "body": "Hello", - "index": 0, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/chat/v1/service/test_channel.py b/tests/integration/chat/v1/service/test_channel.py deleted file mode 100644 index 88069d90d3..0000000000 --- a/tests/integration/chat/v1/service/test_channel.py +++ /dev/null @@ -1,255 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ChannelTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "unique_name": "unique_name", - "attributes": "{ \\"foo\\": \\"bar\\" }", - "type": "public", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:37Z", - "created_by": "system", - "members_count": 0, - "messages_count": 0, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "members": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members", - "messages": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages", - "invites": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites", - "last_message": null - } - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "unique_name": "unique_name", - "attributes": "{ \\"foo\\": \\"bar\\" }", - "type": "public", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:37Z", - "created_by": "system", - "members_count": 0, - "messages_count": 0, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "members": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members", - "messages": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages", - "invites": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites", - "last_message": null - } - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels.create() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "channels": [ - { - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "unique_name": "unique_name", - "attributes": "{ \\"foo\\": \\"bar\\" }", - "type": "public", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:37Z", - "created_by": "system", - "members_count": 0, - "messages_count": 0, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "members": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members", - "messages": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages", - "invites": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites", - "last_message": null - } - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "next_page_url": null, - "key": "channels" - } - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "channels": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "next_page_url": null, - "key": "channels" - } - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "unique_name": "unique_name", - "attributes": "{ \\"foo\\": \\"bar\\" }", - "type": "public", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:37Z", - "created_by": "system", - "members_count": 0, - "messages_count": 0, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "members": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members", - "messages": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages", - "invites": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites", - "last_message": null - } - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/chat/v1/service/test_role.py b/tests/integration/chat/v1/service/test_role.py deleted file mode 100644 index eb801a3764..0000000000 --- a/tests/integration/chat/v1/service/test_role.py +++ /dev/null @@ -1,246 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base import serialize -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class RoleTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles(sid="RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Roles/RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "channel user", - "type": "channel", - "permissions": [ - "sendMessage", - "leaveChannel", - "editOwnMessage", - "deleteOwnMessage" - ], - "date_created": "2016-03-03T19:47:15Z", - "date_updated": "2016-03-03T19:47:15Z", - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles(sid="RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles(sid="RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Roles/RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles(sid="RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles.create(friendly_name="friendly_name", type="channel", permission=['permission']) - - values = { - 'FriendlyName': "friendly_name", - 'Type': "channel", - 'Permission': serialize.map(['permission'], lambda e: e), - } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Roles', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "channel user", - "type": "channel", - "permissions": [ - "sendMessage", - "leaveChannel", - "editOwnMessage", - "deleteOwnMessage" - ], - "date_created": "2016-03-03T19:47:15Z", - "date_updated": "2016-03-03T19:47:15Z", - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles.create(friendly_name="friendly_name", type="channel", permission=['permission']) - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Roles', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=50&Page=0", - "next_page_url": null, - "key": "roles" - }, - "roles": [ - { - "sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "channel user", - "type": "channel", - "permissions": [ - "sendMessage", - "leaveChannel", - "editOwnMessage", - "deleteOwnMessage" - ], - "date_created": "2016-03-03T19:47:15Z", - "date_updated": "2016-03-03T19:47:15Z", - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=50&Page=0", - "next_page_url": null, - "key": "roles" - }, - "roles": [] - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles(sid="RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(permission=['permission']) - - values = {'Permission': serialize.map(['permission'], lambda e: e), } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Roles/RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "channel user", - "type": "channel", - "permissions": [ - "sendMessage", - "leaveChannel", - "editOwnMessage", - "deleteOwnMessage" - ], - "date_created": "2016-03-03T19:47:15Z", - "date_updated": "2016-03-03T19:47:15Z", - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles(sid="RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(permission=['permission']) - - self.assertIsNotNone(actual) diff --git a/tests/integration/chat/v1/service/test_user.py b/tests/integration/chat/v1/service/test_user.py deleted file mode 100644 index 228fe0f6ab..0000000000 --- a/tests/integration/chat/v1/service/test_user.py +++ /dev/null @@ -1,246 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class UserTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "attributes": null, - "is_online": true, - "is_notifiable": null, - "friendly_name": null, - "joined_channels_count": 0, - "date_created": "2016-03-24T21:05:19Z", - "date_updated": "2016-03-24T21:05:19Z", - "links": { - "user_channels": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels" - }, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.create(identity="identity") - - values = {'Identity': "identity", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "attributes": null, - "is_online": true, - "is_notifiable": null, - "friendly_name": null, - "joined_channels_count": 0, - "date_created": "2016-03-24T21:05:19Z", - "date_updated": "2016-03-24T21:05:19Z", - "links": { - "user_channels": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels" - }, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.create(identity="identity") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users?PageSize=50&Page=0", - "next_page_url": null, - "key": "users" - }, - "users": [ - { - "sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "attributes": null, - "is_online": true, - "is_notifiable": null, - "friendly_name": null, - "date_created": "2016-03-24T21:05:19Z", - "date_updated": "2016-03-24T21:05:19Z", - "joined_channels_count": 0, - "links": { - "user_channels": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels" - }, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users?PageSize=50&Page=0", - "next_page_url": null, - "key": "users" - }, - "users": [] - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "attributes": null, - "is_online": true, - "is_notifiable": null, - "friendly_name": null, - "joined_channels_count": 0, - "date_created": "2016-03-24T21:05:19Z", - "date_updated": "2016-03-24T21:05:19Z", - "links": { - "user_channels": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels" - }, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/chat/v1/service/user/__init__.py b/tests/integration/chat/v1/service/user/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/chat/v1/service/user/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/chat/v1/service/user/test_user_channel.py b/tests/integration/chat/v1/service/user/test_user_channel.py deleted file mode 100644 index aa4db70560..0000000000 --- a/tests/integration/chat/v1/service/user/test_user_channel.py +++ /dev/null @@ -1,92 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class UserChannelTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "next_page_url": null, - "key": "channels" - }, - "channels": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "member_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "joined", - "last_consumed_message_index": 5, - "unread_messages_count": 5, - "links": { - "channel": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "member": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - } - ] - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "next_page_url": null, - "key": "channels" - }, - "channels": [] - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/chat/v1/test_credential.py b/tests/integration/chat/v1/test_credential.py deleted file mode 100644 index e0caa7e162..0000000000 --- a/tests/integration/chat/v1/test_credential.py +++ /dev/null @@ -1,203 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class CredentialTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.credentials.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v1/Credentials', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "credentials": [ - { - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Test slow create", - "type": "apn", - "sandbox": "False", - "date_created": "2015-10-07T17:50:01Z", - "date_updated": "2015-10-07T17:50:01Z", - "url": "https://chat.twilio.com/v1/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "page": 0, - "page_size": 1, - "first_page_url": "https://chat.twilio.com/v1/Credentials?PageSize=1&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Credentials?PageSize=1&Page=0", - "next_page_url": null, - "key": "credentials" - } - } - ''' - )) - - actual = self.client.chat.v1.credentials.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "credentials": [], - "meta": { - "page": 0, - "page_size": 1, - "first_page_url": "https://chat.twilio.com/v1/Credentials?PageSize=1&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Credentials?PageSize=1&Page=0", - "next_page_url": null, - "key": "credentials" - } - } - ''' - )) - - actual = self.client.chat.v1.credentials.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.credentials.create(type="gcm") - - values = {'Type': "gcm", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v1/Credentials', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Test slow create", - "type": "apn", - "sandbox": "False", - "date_created": "2015-10-07T17:50:01Z", - "date_updated": "2015-10-07T17:50:01Z", - "url": "https://chat.twilio.com/v1/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v1.credentials.create(type="gcm") - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v1/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Test slow create", - "type": "apn", - "sandbox": "False", - "date_created": "2015-10-07T17:50:01Z", - "date_updated": "2015-10-07T17:50:01Z", - "url": "https://chat.twilio.com/v1/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v1.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v1/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Test slow create", - "type": "apn", - "sandbox": "False", - "date_created": "2015-10-07T17:50:01Z", - "date_updated": "2015-10-07T17:50:01Z", - "url": "https://chat.twilio.com/v1/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v1.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v1/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.chat.v1.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/chat/v1/test_service.py b/tests/integration/chat/v1/test_service.py deleted file mode 100644 index d2cfe4c5f1..0000000000 --- a/tests/integration/chat/v1/test_service.py +++ /dev/null @@ -1,279 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ServiceTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "consumption_report_interval": 100, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "default_channel_creator_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_channel_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_service_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "limits": { - "actions_per_second": 20, - "channel_members": 100, - "user_channels": 250 - }, - "links": {}, - "notifications": {}, - "post_webhook_url": "post_webhook_url", - "pre_webhook_url": "pre_webhook_url", - "reachability_enabled": false, - "read_status_enabled": false, - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "typing_indicator_timeout": 100, - "url": "http://www.example.com", - "webhook_filters": [ - "webhook_filters" - ], - "webhook_method": "webhook_method", - "webhooks": {} - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services.create(friendly_name="friendly_name") - - values = {'FriendlyName': "friendly_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v1/Services', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "consumption_report_interval": 100, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "default_channel_creator_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_channel_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_service_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "limits": { - "actions_per_second": 20, - "channel_members": 100, - "user_channels": 250 - }, - "links": {}, - "notifications": {}, - "post_webhook_url": "post_webhook_url", - "pre_webhook_url": "pre_webhook_url", - "reachability_enabled": false, - "read_status_enabled": false, - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "typing_indicator_timeout": 100, - "url": "http://www.example.com", - "webhook_filters": [ - "webhook_filters" - ], - "webhook_method": "webhook_method", - "webhooks": {} - } - ''' - )) - - actual = self.client.chat.v1.services.create(friendly_name="friendly_name") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v1/Services', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://chat.twilio.com/v1/Services?Page=0&PageSize=50", - "key": "services", - "next_page_url": null, - "page": 0, - "page_size": 0, - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services" - }, - "services": [] - } - ''' - )) - - actual = self.client.chat.v1.services.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://chat.twilio.com/v1/Services?Page=0&PageSize=50", - "key": "services", - "next_page_url": null, - "page": 0, - "page_size": 1, - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services" - }, - "services": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "consumption_report_interval": 100, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "default_channel_creator_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_channel_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_service_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "limits": { - "actions_per_second": 20, - "channel_members": 100, - "user_channels": 250 - }, - "links": {}, - "notifications": {}, - "post_webhook_url": "post_webhook_url", - "pre_webhook_url": "pre_webhook_url", - "reachability_enabled": false, - "read_status_enabled": false, - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "typing_indicator_timeout": 100, - "url": "http://www.example.com", - "webhook_filters": [ - "webhook_filters" - ], - "webhook_method": "webhook_method", - "webhooks": {} - } - ] - } - ''' - )) - - actual = self.client.chat.v1.services.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "consumption_report_interval": 100, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "default_channel_creator_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_channel_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_service_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "limits": { - "actions_per_second": 20, - "channel_members": 500, - "user_channels": 600 - }, - "links": {}, - "notifications": {}, - "post_webhook_url": "post_webhook_url", - "pre_webhook_url": "pre_webhook_url", - "reachability_enabled": false, - "read_status_enabled": false, - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "typing_indicator_timeout": 100, - "url": "http://www.example.com", - "webhook_filters": [ - "webhook_filters" - ], - "webhook_method": "webhook_method", - "webhooks": {} - } - ''' - )) - - actual = self.client.chat.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/chat/v2/__init__.py b/tests/integration/chat/v2/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/chat/v2/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/chat/v2/service/__init__.py b/tests/integration/chat/v2/service/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/chat/v2/service/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/chat/v2/service/channel/__init__.py b/tests/integration/chat/v2/service/channel/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/chat/v2/service/channel/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/chat/v2/service/channel/test_invite.py b/tests/integration/chat/v2/service/channel/test_invite.py deleted file mode 100644 index 905b478dd0..0000000000 --- a/tests/integration/chat/v2/service/channel/test_invite.py +++ /dev/null @@ -1,195 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class InviteTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites(sid="INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Invites/INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "identity": "identity", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites/INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites(sid="INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites.create(identity="identity") - - values = {'Identity': "identity", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Invites', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "identity": "identity", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites/INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites.create(identity="identity") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Invites', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "invites": [], - "meta": { - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0", - "key": "invites", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "invites": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "identity": "identity", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites/INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0", - "key": "invites", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites.list() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites(sid="INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Invites/INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites(sid="INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/chat/v2/service/channel/test_member.py b/tests/integration/chat/v2/service/channel/test_member.py deleted file mode 100644 index 3d38190b28..0000000000 --- a/tests/integration/chat/v2/service/channel/test_member.py +++ /dev/null @@ -1,237 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class MemberTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members/MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "last_consumed_message_index": null, - "last_consumption_timestamp": null, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members.create(identity="identity") - - values = {'Identity': "identity", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "last_consumed_message_index": null, - "last_consumption_timestamp": null, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members.create(identity="identity") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0", - "next_page_url": null, - "key": "members" - }, - "members": [ - { - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "last_consumed_message_index": null, - "last_consumption_timestamp": null, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0", - "next_page_url": null, - "key": "members" - }, - "members": [] - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members.list() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members/MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members/MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_role_sid_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "last_consumed_message_index": 20, - "last_consumption_timestamp": "2016-03-24T21:05:52Z", - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:51Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/chat/v2/service/channel/test_message.py b/tests/integration/chat/v2/service/channel/test_message.py deleted file mode 100644 index 453fb48a55..0000000000 --- a/tests/integration/chat/v2/service/channel/test_message.py +++ /dev/null @@ -1,380 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class MessageTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "last_updated_by": null, - "was_edited": false, - "from": "system", - "attributes": "{}", - "body": "Hello", - "index": 0, - "type": "text", - "media": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_fetch_media_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "last_updated_by": null, - "was_edited": false, - "from": "system", - "attributes": "{}", - "body": "Hello", - "index": 0, - "type": "media", - "media": { - "sid": "MEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "size": 99999999999999, - "content_type": "application/pdf", - "filename": "hello.pdf" - }, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "attributes": null, - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "last_updated_by": "system", - "was_edited": false, - "from": "system", - "body": "Hello", - "index": 0, - "type": "text", - "media": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.create() - - self.assertIsNotNone(actual) - - def test_create_with_all_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:38Z", - "last_updated_by": "username", - "was_edited": true, - "from": "system", - "attributes": "{\\"test\\": \\"test\\"}", - "body": "Hello", - "index": 0, - "type": "text", - "media": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.create() - - self.assertIsNotNone(actual) - - def test_create_media_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "attributes": null, - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "last_updated_by": "system", - "was_edited": false, - "from": "system", - "body": "Hello", - "index": 0, - "type": "text", - "media": { - "sid": "MEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "size": 99999999999999, - "content_type": "application/pdf", - "filename": "hello.pdf" - }, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.create() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages?PageSize=50&Page=0", - "next_page_url": null, - "key": "messages" - }, - "messages": [ - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "last_updated_by": null, - "was_edited": false, - "from": "system", - "attributes": "{}", - "body": "Hello", - "index": 0, - "type": "text", - "media": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "last_updated_by": null, - "was_edited": false, - "from": "system", - "attributes": "{}", - "body": "Hello", - "index": 0, - "type": "media", - "media": { - "sid": "MEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "size": 99999999999999, - "content_type": "application/pdf", - "filename": "hello.pdf" - }, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages?PageSize=50&Page=0", - "next_page_url": null, - "key": "messages" - }, - "messages": [] - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.list() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "attributes": "{ \\"foo\\": \\"bar\\" }", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:38Z", - "last_updated_by": "username", - "was_edited": true, - "from": "system", - "body": "Hello", - "index": 0, - "type": "text", - "media": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/chat/v2/service/test_binding.py b/tests/integration/chat/v2/service/test_binding.py deleted file mode 100644 index 799de93e1a..0000000000 --- a/tests/integration/chat/v2/service/test_binding.py +++ /dev/null @@ -1,165 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class BindingTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings?PageSize=50&Page=0", - "next_page_url": null, - "key": "bindings" - }, - "bindings": [ - { - "sid": "BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-10-21T11:37:03Z", - "date_updated": "2016-10-21T11:37:03Z", - "endpoint": "TestUser-endpoint", - "identity": "TestUser", - "binding_type": "gcm", - "credential_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "message_types": [ - "removed_from_channel", - "new_message", - "added_to_channel", - "invited_to_channel" - ], - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings/BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "user": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/TestUser" - } - } - ] - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings?PageSize=50&Page=0", - "next_page_url": null, - "key": "bindings" - }, - "bindings": [] - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings(sid="BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings/BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-10-21T11:37:03Z", - "date_updated": "2016-10-21T11:37:03Z", - "endpoint": "TestUser-endpoint", - "identity": "TestUser", - "binding_type": "gcm", - "credential_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "message_types": [ - "removed_from_channel", - "new_message", - "added_to_channel", - "invited_to_channel" - ], - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings/BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "user": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/TestUser" - } - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings(sid="BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings(sid="BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings/BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings(sid="BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/chat/v2/service/test_channel.py b/tests/integration/chat/v2/service/test_channel.py deleted file mode 100644 index ceb518b5dc..0000000000 --- a/tests/integration/chat/v2/service/test_channel.py +++ /dev/null @@ -1,255 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ChannelTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "unique_name": "unique_name", - "attributes": "{ \\"foo\\": \\"bar\\" }", - "type": "public", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:37Z", - "created_by": "system", - "members_count": 0, - "messages_count": 0, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "members": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members", - "messages": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages", - "invites": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites", - "last_message": null - } - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "unique_name": "unique_name", - "attributes": "{ \\"foo\\": \\"bar\\" }", - "type": "public", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:38Z", - "created_by": "username", - "members_count": 0, - "messages_count": 0, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "members": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members", - "messages": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages", - "invites": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites", - "last_message": null - } - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels.create() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "channels": [ - { - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "unique_name": "unique_name", - "attributes": "{ \\"foo\\": \\"bar\\" }", - "type": "public", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:37Z", - "created_by": "system", - "members_count": 0, - "messages_count": 0, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "members": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members", - "messages": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages", - "invites": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites", - "last_message": null - } - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "next_page_url": null, - "key": "channels" - } - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "channels": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "next_page_url": null, - "key": "channels" - } - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "unique_name": "unique_name", - "attributes": "{ \\"foo\\": \\"bar\\" }", - "type": "public", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:38Z", - "created_by": "username", - "members_count": 0, - "messages_count": 0, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "members": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members", - "messages": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages", - "invites": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites", - "last_message": null - } - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/chat/v2/service/test_role.py b/tests/integration/chat/v2/service/test_role.py deleted file mode 100644 index 46d4ada9b3..0000000000 --- a/tests/integration/chat/v2/service/test_role.py +++ /dev/null @@ -1,246 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base import serialize -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class RoleTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles(sid="RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Roles/RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "channel user", - "type": "channel", - "permissions": [ - "sendMessage", - "leaveChannel", - "editOwnMessage", - "deleteOwnMessage" - ], - "date_created": "2016-03-03T19:47:15Z", - "date_updated": "2016-03-03T19:47:15Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles(sid="RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles(sid="RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Roles/RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles(sid="RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles.create(friendly_name="friendly_name", type="channel", permission=['permission']) - - values = { - 'FriendlyName': "friendly_name", - 'Type': "channel", - 'Permission': serialize.map(['permission'], lambda e: e), - } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Roles', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "channel user", - "type": "channel", - "permissions": [ - "sendMessage", - "leaveChannel", - "editOwnMessage", - "deleteOwnMessage" - ], - "date_created": "2016-03-03T19:47:15Z", - "date_updated": "2016-03-03T19:47:15Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles.create(friendly_name="friendly_name", type="channel", permission=['permission']) - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Roles', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=50&Page=0", - "next_page_url": null, - "key": "roles" - }, - "roles": [ - { - "sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "channel user", - "type": "channel", - "permissions": [ - "sendMessage", - "leaveChannel", - "editOwnMessage", - "deleteOwnMessage" - ], - "date_created": "2016-03-03T19:47:15Z", - "date_updated": "2016-03-03T19:47:15Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=50&Page=0", - "next_page_url": null, - "key": "roles" - }, - "roles": [] - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles(sid="RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(permission=['permission']) - - values = {'Permission': serialize.map(['permission'], lambda e: e), } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Roles/RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "channel user", - "type": "channel", - "permissions": [ - "sendMessage", - "leaveChannel", - "editOwnMessage", - "deleteOwnMessage" - ], - "date_created": "2016-03-03T19:47:15Z", - "date_updated": "2016-03-03T19:47:15Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles(sid="RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(permission=['permission']) - - self.assertIsNotNone(actual) diff --git a/tests/integration/chat/v2/service/test_user.py b/tests/integration/chat/v2/service/test_user.py deleted file mode 100644 index e90dbcf1fa..0000000000 --- a/tests/integration/chat/v2/service/test_user.py +++ /dev/null @@ -1,250 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class UserTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "attributes": null, - "is_online": true, - "is_notifiable": null, - "friendly_name": null, - "joined_channels_count": 0, - "date_created": "2016-03-24T21:05:19Z", - "date_updated": "2016-03-24T21:05:19Z", - "links": { - "user_channels": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels", - "user_bindings": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings" - }, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.create(identity="identity") - - values = {'Identity': "identity", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "attributes": null, - "is_online": true, - "is_notifiable": null, - "friendly_name": null, - "joined_channels_count": 0, - "date_created": "2016-03-24T21:05:19Z", - "date_updated": "2016-03-24T21:05:19Z", - "links": { - "user_channels": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels", - "user_bindings": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings" - }, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.create(identity="identity") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users?PageSize=50&Page=0", - "next_page_url": null, - "key": "users" - }, - "users": [ - { - "sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "attributes": null, - "is_online": true, - "is_notifiable": null, - "friendly_name": null, - "date_created": "2016-03-24T21:05:19Z", - "date_updated": "2016-03-24T21:05:19Z", - "joined_channels_count": 0, - "links": { - "user_channels": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels", - "user_bindings": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings" - }, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users?PageSize=50&Page=0", - "next_page_url": null, - "key": "users" - }, - "users": [] - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "attributes": null, - "is_online": true, - "is_notifiable": null, - "friendly_name": null, - "joined_channels_count": 0, - "date_created": "2016-03-24T21:05:19Z", - "date_updated": "2016-03-24T21:05:19Z", - "links": { - "user_channels": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels", - "user_bindings": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings" - }, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/chat/v2/service/user/__init__.py b/tests/integration/chat/v2/service/user/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/chat/v2/service/user/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/chat/v2/service/user/test_user_binding.py b/tests/integration/chat/v2/service/user/test_user_binding.py deleted file mode 100644 index 0d9154a157..0000000000 --- a/tests/integration/chat/v2/service/user/test_user_binding.py +++ /dev/null @@ -1,168 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class UserBindingTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_bindings.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings?PageSize=50&Page=0", - "next_page_url": null, - "key": "bindings" - }, - "bindings": [ - { - "sid": "BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-10-21T11:37:03Z", - "date_updated": "2016-10-21T11:37:03Z", - "endpoint": "TestUser-endpoint", - "identity": "TestUser", - "user_sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "binding_type": "gcm", - "credential_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "message_types": [ - "removed_from_channel", - "new_message", - "added_to_channel", - "invited_to_channel" - ], - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings/BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_bindings.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings?PageSize=50&Page=0", - "next_page_url": null, - "key": "bindings" - }, - "bindings": [] - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_bindings.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_bindings(sid="BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings/BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-10-21T11:37:03Z", - "date_updated": "2016-10-21T11:37:03Z", - "endpoint": "TestUser-endpoint", - "identity": "TestUser", - "user_sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "binding_type": "gcm", - "credential_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "message_types": [ - "removed_from_channel", - "new_message", - "added_to_channel", - "invited_to_channel" - ], - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings/BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_bindings(sid="BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_bindings(sid="BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings/BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_bindings(sid="BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/chat/v2/service/user/test_user_channel.py b/tests/integration/chat/v2/service/user/test_user_channel.py deleted file mode 100644 index ac26232d61..0000000000 --- a/tests/integration/chat/v2/service/user/test_user_channel.py +++ /dev/null @@ -1,92 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class UserChannelTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "next_page_url": null, - "key": "channels" - }, - "channels": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "member_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "joined", - "last_consumed_message_index": 5, - "unread_messages_count": 5, - "links": { - "channel": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "member": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - } - ] - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "next_page_url": null, - "key": "channels" - }, - "channels": [] - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/chat/v2/test_credential.py b/tests/integration/chat/v2/test_credential.py deleted file mode 100644 index fe260c2c23..0000000000 --- a/tests/integration/chat/v2/test_credential.py +++ /dev/null @@ -1,203 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class CredentialTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.credentials.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Credentials', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "credentials": [ - { - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Test slow create", - "type": "apn", - "sandbox": "False", - "date_created": "2015-10-07T17:50:01Z", - "date_updated": "2015-10-07T17:50:01Z", - "url": "https://chat.twilio.com/v2/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "page": 0, - "page_size": 1, - "first_page_url": "https://chat.twilio.com/v2/Credentials?PageSize=1&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Credentials?PageSize=1&Page=0", - "next_page_url": null, - "key": "credentials" - } - } - ''' - )) - - actual = self.client.chat.v2.credentials.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "credentials": [], - "meta": { - "page": 0, - "page_size": 1, - "first_page_url": "https://chat.twilio.com/v2/Credentials?PageSize=1&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Credentials?PageSize=1&Page=0", - "next_page_url": null, - "key": "credentials" - } - } - ''' - )) - - actual = self.client.chat.v2.credentials.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.credentials.create(type="gcm") - - values = {'Type': "gcm", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Credentials', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Test slow create", - "type": "apn", - "sandbox": "False", - "date_created": "2015-10-07T17:50:01Z", - "date_updated": "2015-10-07T17:50:01Z", - "url": "https://chat.twilio.com/v2/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.credentials.create(type="gcm") - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Test slow create", - "type": "apn", - "sandbox": "False", - "date_created": "2015-10-07T17:50:01Z", - "date_updated": "2015-10-07T17:50:01Z", - "url": "https://chat.twilio.com/v2/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Test slow create", - "type": "apn", - "sandbox": "False", - "date_created": "2015-10-07T17:50:01Z", - "date_updated": "2015-10-07T17:50:01Z", - "url": "https://chat.twilio.com/v2/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v2/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.chat.v2.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/chat/v2/test_service.py b/tests/integration/chat/v2/test_service.py deleted file mode 100644 index e8a867d549..0000000000 --- a/tests/integration/chat/v2/test_service.py +++ /dev/null @@ -1,334 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ServiceTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "consumption_report_interval": 100, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "default_channel_creator_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_channel_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_service_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "limits": { - "channel_members": 100, - "user_channels": 250 - }, - "links": { - "channels": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels", - "users": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users", - "roles": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles", - "bindings": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings" - }, - "notifications": {}, - "post_webhook_url": "post_webhook_url", - "pre_webhook_url": "pre_webhook_url", - "pre_webhook_retry_count": 2, - "post_webhook_retry_count": 3, - "reachability_enabled": false, - "read_status_enabled": false, - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "typing_indicator_timeout": 100, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "webhook_filters": [ - "webhook_filters" - ], - "webhook_method": "webhook_method", - "media": { - "size_limit_mb": 150, - "compatibility_message": "media compatibility message" - } - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services.create(friendly_name="friendly_name") - - values = {'FriendlyName': "friendly_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "consumption_report_interval": 100, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "default_channel_creator_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_channel_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_service_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "limits": { - "channel_members": 100, - "user_channels": 250 - }, - "links": { - "channels": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels", - "users": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users", - "roles": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles", - "bindings": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings" - }, - "notifications": {}, - "post_webhook_url": "post_webhook_url", - "pre_webhook_url": "pre_webhook_url", - "pre_webhook_retry_count": 2, - "post_webhook_retry_count": 3, - "reachability_enabled": false, - "read_status_enabled": false, - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "typing_indicator_timeout": 100, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "webhook_filters": [ - "webhook_filters" - ], - "webhook_method": "webhook_method", - "media": { - "size_limit_mb": 150, - "compatibility_message": "media compatibility message" - } - } - ''' - )) - - actual = self.client.chat.v2.services.create(friendly_name="friendly_name") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Services', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://chat.twilio.com/v2/Services?PageSize=50&Page=0", - "key": "services", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services?PageSize=50&Page=0" - }, - "services": [] - } - ''' - )) - - actual = self.client.chat.v2.services.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://chat.twilio.com/v2/Services?PageSize=50&Page=0", - "key": "services", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services?PageSize=50&Page=0" - }, - "services": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "consumption_report_interval": 100, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "default_channel_creator_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_channel_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_service_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "limits": { - "channel_members": 100, - "user_channels": 250 - }, - "links": { - "channels": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels", - "users": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users", - "roles": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles", - "bindings": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings" - }, - "notifications": {}, - "post_webhook_url": "post_webhook_url", - "pre_webhook_url": "pre_webhook_url", - "pre_webhook_retry_count": 2, - "post_webhook_retry_count": 3, - "reachability_enabled": false, - "read_status_enabled": false, - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "typing_indicator_timeout": 100, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "webhook_filters": [ - "webhook_filters" - ], - "webhook_method": "webhook_method", - "media": { - "size_limit_mb": 150, - "compatibility_message": "media compatibility message" - } - } - ] - } - ''' - )) - - actual = self.client.chat.v2.services.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "consumption_report_interval": 100, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "default_channel_creator_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_channel_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_service_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "limits": { - "channel_members": 500, - "user_channels": 600 - }, - "links": { - "channels": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels", - "users": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users", - "roles": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles", - "bindings": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings" - }, - "notifications": { - "log_enabled": true, - "added_to_channel": { - "enabled": false, - "template": "notifications.added_to_channel.template" - }, - "invited_to_channel": { - "enabled": false, - "template": "notifications.invited_to_channel.template" - }, - "new_message": { - "enabled": false, - "template": "notifications.new_message.template", - "badge_count_enabled": true - }, - "removed_from_channel": { - "enabled": false, - "template": "notifications.removed_from_channel.template" - } - }, - "post_webhook_url": "post_webhook_url", - "pre_webhook_url": "pre_webhook_url", - "pre_webhook_retry_count": 2, - "post_webhook_retry_count": 3, - "reachability_enabled": false, - "read_status_enabled": false, - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "typing_indicator_timeout": 100, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "webhook_filters": [ - "webhook_filters" - ], - "webhook_method": "webhook_method", - "media": { - "size_limit_mb": 150, - "compatibility_message": "new media compatibility message" - } - } - ''' - )) - - actual = self.client.chat.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/fax/__init__.py b/tests/integration/fax/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/fax/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/fax/v1/__init__.py b/tests/integration/fax/v1/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/fax/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/fax/v1/fax/__init__.py b/tests/integration/fax/v1/fax/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/fax/v1/fax/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/fax/v1/fax/test_fax_media.py b/tests/integration/fax/v1/fax/test_fax_media.py deleted file mode 100644 index eb777d8f09..0000000000 --- a/tests/integration/fax/v1/fax/test_fax_media.py +++ /dev/null @@ -1,117 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class FaxMediaTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.fax.v1.faxes(sid="FXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .media(sid="MEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://fax.twilio.com/v1/Faxes/FXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Media/MEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "content_type": "application/pdf", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "fax_sid": "FXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "MEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://fax.twilio.com/v1/Faxes/FXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media/MEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.fax.v1.faxes(sid="FXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .media(sid="MEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.fax.v1.faxes(sid="FXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .media.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://fax.twilio.com/v1/Faxes/FXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Media', - )) - - def test_read_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "media": [ - { - "sid": "MEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "fax_sid": "FXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "content_type": "application/pdf", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://fax.twilio.com/v1/Faxes/FXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media/MEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://fax.twilio.com/v1/Faxes/FXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media?PageSize=50&Page=0", - "key": "media", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://fax.twilio.com/v1/Faxes/FXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.fax.v1.faxes(sid="FXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .media.list() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.fax.v1.faxes(sid="FXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .media(sid="MEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://fax.twilio.com/v1/Faxes/FXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Media/MEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.fax.v1.faxes(sid="FXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .media(sid="MEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/fax/v1/test_fax.py b/tests/integration/fax/v1/test_fax.py deleted file mode 100644 index ba0f1f2e62..0000000000 --- a/tests/integration/fax/v1/test_fax.py +++ /dev/null @@ -1,251 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class FaxTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.fax.v1.faxes(sid="FXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://fax.twilio.com/v1/Faxes/FXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "v1", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "direction": "outbound", - "from": "+14155551234", - "media_url": "https://www.example.com/fax.pdf", - "media_sid": "MEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "num_pages": null, - "price": null, - "price_unit": null, - "quality": null, - "sid": "FXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "queued", - "to": "+14155554321", - "duration": null, - "links": { - "media": "https://fax.twilio.com/v1/Faxes/FXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media" - }, - "url": "https://fax.twilio.com/v1/Faxes/FXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.fax.v1.faxes(sid="FXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.fax.v1.faxes.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://fax.twilio.com/v1/Faxes', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "faxes": [], - "meta": { - "first_page_url": "https://fax.twilio.com/v1/Faxes?PageSize=50&Page=0", - "key": "faxes", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://fax.twilio.com/v1/Faxes?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.fax.v1.faxes.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "faxes": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "v1", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "direction": "outbound", - "from": "+14155551234", - "media_url": "https://www.example.com/fax.pdf", - "media_sid": "MEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "num_pages": null, - "price": null, - "price_unit": null, - "quality": null, - "sid": "FXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "queued", - "to": "+14155554321", - "duration": null, - "links": { - "media": "https://fax.twilio.com/v1/Faxes/FXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media" - }, - "url": "https://fax.twilio.com/v1/Faxes/FXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://fax.twilio.com/v1/Faxes?PageSize=50&Page=0", - "key": "faxes", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://fax.twilio.com/v1/Faxes?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.fax.v1.faxes.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.fax.v1.faxes.create(to="to", media_url="https://example.com") - - values = {'To': "to", 'MediaUrl': "https://example.com", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://fax.twilio.com/v1/Faxes', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "v1", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "direction": "outbound", - "from": "+14155551234", - "media_url": null, - "media_sid": null, - "num_pages": null, - "price": null, - "price_unit": null, - "quality": "superfine", - "sid": "FXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "queued", - "to": "+14155554321", - "duration": null, - "links": { - "media": "https://fax.twilio.com/v1/Faxes/FXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media" - }, - "url": "https://fax.twilio.com/v1/Faxes/FXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.fax.v1.faxes.create(to="to", media_url="https://example.com") - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.fax.v1.faxes(sid="FXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://fax.twilio.com/v1/Faxes/FXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "v1", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "direction": "outbound", - "from": "+14155551234", - "media_url": null, - "media_sid": null, - "num_pages": null, - "price": null, - "price_unit": null, - "quality": null, - "sid": "FXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "canceled", - "to": "+14155554321", - "duration": null, - "links": { - "media": "https://fax.twilio.com/v1/Faxes/FXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media" - }, - "url": "https://fax.twilio.com/v1/Faxes/FXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.fax.v1.faxes(sid="FXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.fax.v1.faxes(sid="FXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://fax.twilio.com/v1/Faxes/FXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.fax.v1.faxes(sid="FXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/ip_messaging/__init__.py b/tests/integration/ip_messaging/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/ip_messaging/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/ip_messaging/v1/__init__.py b/tests/integration/ip_messaging/v1/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/ip_messaging/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/ip_messaging/v1/service/__init__.py b/tests/integration/ip_messaging/v1/service/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/ip_messaging/v1/service/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/ip_messaging/v1/service/channel/__init__.py b/tests/integration/ip_messaging/v1/service/channel/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/ip_messaging/v1/service/channel/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/ip_messaging/v1/service/channel/test_invite.py b/tests/integration/ip_messaging/v1/service/channel/test_invite.py deleted file mode 100644 index 54a50d3d4f..0000000000 --- a/tests/integration/ip_messaging/v1/service/channel/test_invite.py +++ /dev/null @@ -1,195 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class InviteTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites(sid="INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Invites/INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "identity": "identity", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites/INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites(sid="INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites.create(identity="identity") - - values = {'Identity': "identity", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Invites', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "identity": "identity", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites/INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites.create(identity="identity") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Invites', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "invites": [], - "meta": { - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0", - "key": "invites", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "invites": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "identity": "identity", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites/INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0", - "key": "invites", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites.list() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites(sid="INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Invites/INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites(sid="INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/ip_messaging/v1/service/channel/test_member.py b/tests/integration/ip_messaging/v1/service/channel/test_member.py deleted file mode 100644 index 80e6c42f44..0000000000 --- a/tests/integration/ip_messaging/v1/service/channel/test_member.py +++ /dev/null @@ -1,263 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class MemberTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members/MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "last_consumed_message_index": null, - "last_consumption_timestamp": null, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members.create(identity="identity") - - values = {'Identity': "identity", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "last_consumed_message_index": null, - "last_consumption_timestamp": null, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members.create(identity="identity") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0", - "next_page_url": null, - "key": "members" - }, - "members": [ - { - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "last_consumed_message_index": null, - "last_consumption_timestamp": null, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0", - "next_page_url": null, - "key": "members" - }, - "members": [] - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members.list() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members/MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members/MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_role_sid_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "last_consumed_message_index": null, - "last_consumption_timestamp": null, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_update_last_consumed_message_index_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "last_consumed_message_index": 666, - "last_consumption_timestamp": null, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/ip_messaging/v1/service/channel/test_message.py b/tests/integration/ip_messaging/v1/service/channel/test_message.py deleted file mode 100644 index 30c031ee7a..0000000000 --- a/tests/integration/ip_messaging/v1/service/channel/test_message.py +++ /dev/null @@ -1,273 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class MessageTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "was_edited": false, - "from": "system", - "attributes": "{}", - "body": "Hello", - "index": 0, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.create(body="body") - - values = {'Body': "body", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "attributes": null, - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "was_edited": false, - "from": "system", - "body": "Hello", - "index": 0, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.create(body="body") - - self.assertIsNotNone(actual) - - def test_create_with_attributes_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "was_edited": false, - "from": "system", - "attributes": "{}", - "body": "Hello", - "index": 0, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.create(body="body") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages?PageSize=50&Page=0", - "next_page_url": null, - "key": "messages" - }, - "messages": [ - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "was_edited": false, - "from": "system", - "attributes": "{}", - "body": "Hello", - "index": 0, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages?PageSize=50&Page=0", - "next_page_url": null, - "key": "messages" - }, - "messages": [] - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.list() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "attributes": "{\\"test\\": \\"test\\"}", - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "was_edited": false, - "from": "system", - "body": "Hello", - "index": 0, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/ip_messaging/v1/service/test_channel.py b/tests/integration/ip_messaging/v1/service/test_channel.py deleted file mode 100644 index 779147f3fb..0000000000 --- a/tests/integration/ip_messaging/v1/service/test_channel.py +++ /dev/null @@ -1,255 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ChannelTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "unique_name": "unique_name", - "attributes": "{ \\"foo\\": \\"bar\\" }", - "type": "public", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:37Z", - "created_by": "system", - "members_count": 0, - "messages_count": 0, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "members": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members", - "messages": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages", - "invites": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites", - "last_message": null - } - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "unique_name": "unique_name", - "attributes": "{ \\"foo\\": \\"bar\\" }", - "type": "public", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:37Z", - "created_by": "system", - "members_count": 0, - "messages_count": 0, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "members": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members", - "messages": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages", - "invites": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites", - "last_message": null - } - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels.create() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "channels": [ - { - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "unique_name": "unique_name", - "attributes": "{ \\"foo\\": \\"bar\\" }", - "type": "public", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:37Z", - "created_by": "system", - "members_count": 0, - "messages_count": 0, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "members": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members", - "messages": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages", - "invites": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites", - "last_message": null - } - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "next_page_url": null, - "key": "channels" - } - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "channels": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "next_page_url": null, - "key": "channels" - } - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "unique_name": "unique_name", - "attributes": "{ \\"foo\\": \\"bar\\" }", - "type": "public", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:37Z", - "created_by": "system", - "members_count": 0, - "messages_count": 0, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "members": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members", - "messages": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages", - "invites": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites", - "last_message": null - } - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/ip_messaging/v1/service/test_role.py b/tests/integration/ip_messaging/v1/service/test_role.py deleted file mode 100644 index e18cbb36fb..0000000000 --- a/tests/integration/ip_messaging/v1/service/test_role.py +++ /dev/null @@ -1,246 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base import serialize -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class RoleTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles(sid="RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Roles/RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "channel user", - "type": "channel", - "permissions": [ - "sendMessage", - "leaveChannel", - "editOwnMessage", - "deleteOwnMessage" - ], - "date_created": "2016-03-03T19:47:15Z", - "date_updated": "2016-03-03T19:47:15Z", - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles(sid="RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles(sid="RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Roles/RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles(sid="RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles.create(friendly_name="friendly_name", type="channel", permission=['permission']) - - values = { - 'FriendlyName': "friendly_name", - 'Type': "channel", - 'Permission': serialize.map(['permission'], lambda e: e), - } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Roles', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "channel user", - "type": "channel", - "permissions": [ - "sendMessage", - "leaveChannel", - "editOwnMessage", - "deleteOwnMessage" - ], - "date_created": "2016-03-03T19:47:15Z", - "date_updated": "2016-03-03T19:47:15Z", - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles.create(friendly_name="friendly_name", type="channel", permission=['permission']) - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Roles', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=50&Page=0", - "next_page_url": null, - "key": "roles" - }, - "roles": [ - { - "sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "channel user", - "type": "channel", - "permissions": [ - "sendMessage", - "leaveChannel", - "editOwnMessage", - "deleteOwnMessage" - ], - "date_created": "2016-03-03T19:47:15Z", - "date_updated": "2016-03-03T19:47:15Z", - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=50&Page=0", - "next_page_url": null, - "key": "roles" - }, - "roles": [] - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles(sid="RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(permission=['permission']) - - values = {'Permission': serialize.map(['permission'], lambda e: e), } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Roles/RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "channel user", - "type": "channel", - "permissions": [ - "sendMessage", - "leaveChannel", - "editOwnMessage", - "deleteOwnMessage" - ], - "date_created": "2016-03-03T19:47:15Z", - "date_updated": "2016-03-03T19:47:15Z", - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles(sid="RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(permission=['permission']) - - self.assertIsNotNone(actual) diff --git a/tests/integration/ip_messaging/v1/service/test_user.py b/tests/integration/ip_messaging/v1/service/test_user.py deleted file mode 100644 index ccb51b8eec..0000000000 --- a/tests/integration/ip_messaging/v1/service/test_user.py +++ /dev/null @@ -1,246 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class UserTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "attributes": null, - "is_online": true, - "is_notifiable": null, - "friendly_name": null, - "joined_channels_count": 0, - "date_created": "2016-03-24T21:05:19Z", - "date_updated": "2016-03-24T21:05:19Z", - "links": { - "user_channels": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels" - }, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.create(identity="identity") - - values = {'Identity': "identity", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "attributes": null, - "is_online": true, - "is_notifiable": null, - "friendly_name": null, - "joined_channels_count": 0, - "date_created": "2016-03-24T21:05:19Z", - "date_updated": "2016-03-24T21:05:19Z", - "links": { - "user_channels": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels" - }, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.create(identity="identity") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users?PageSize=50&Page=0", - "next_page_url": null, - "key": "users" - }, - "users": [ - { - "sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "attributes": null, - "is_online": true, - "is_notifiable": null, - "friendly_name": null, - "date_created": "2016-03-24T21:05:19Z", - "date_updated": "2016-03-24T21:05:19Z", - "joined_channels_count": 0, - "links": { - "user_channels": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels" - }, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users?PageSize=50&Page=0", - "next_page_url": null, - "key": "users" - }, - "users": [] - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "attributes": null, - "is_online": true, - "is_notifiable": null, - "friendly_name": null, - "joined_channels_count": 0, - "date_created": "2016-03-24T21:05:19Z", - "date_updated": "2016-03-24T21:05:19Z", - "links": { - "user_channels": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels" - }, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/ip_messaging/v1/service/user/__init__.py b/tests/integration/ip_messaging/v1/service/user/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/ip_messaging/v1/service/user/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/ip_messaging/v1/service/user/test_user_channel.py b/tests/integration/ip_messaging/v1/service/user/test_user_channel.py deleted file mode 100644 index d53d764bbc..0000000000 --- a/tests/integration/ip_messaging/v1/service/user/test_user_channel.py +++ /dev/null @@ -1,92 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class UserChannelTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "next_page_url": null, - "key": "channels" - }, - "channels": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "member_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "joined", - "last_consumed_message_index": 5, - "unread_messages_count": 5, - "links": { - "channel": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "member": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - } - ] - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "next_page_url": null, - "key": "channels" - }, - "channels": [] - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/ip_messaging/v1/test_credential.py b/tests/integration/ip_messaging/v1/test_credential.py deleted file mode 100644 index d66103c6c7..0000000000 --- a/tests/integration/ip_messaging/v1/test_credential.py +++ /dev/null @@ -1,203 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class CredentialTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.credentials.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v1/Credentials', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "credentials": [ - { - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Test slow create", - "type": "apn", - "sandbox": "False", - "date_created": "2015-10-07T17:50:01Z", - "date_updated": "2015-10-07T17:50:01Z", - "url": "https://chat.twilio.com/v1/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "page": 0, - "page_size": 1, - "first_page_url": "https://chat.twilio.com/v1/Credentials?PageSize=1&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Credentials?PageSize=1&Page=0", - "next_page_url": null, - "key": "credentials" - } - } - ''' - )) - - actual = self.client.ip_messaging.v1.credentials.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "credentials": [], - "meta": { - "page": 0, - "page_size": 1, - "first_page_url": "https://chat.twilio.com/v1/Credentials?PageSize=1&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Credentials?PageSize=1&Page=0", - "next_page_url": null, - "key": "credentials" - } - } - ''' - )) - - actual = self.client.ip_messaging.v1.credentials.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.credentials.create(type="gcm") - - values = {'Type': "gcm", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v1/Credentials', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Test slow create", - "type": "apn", - "sandbox": "False", - "date_created": "2015-10-07T17:50:01Z", - "date_updated": "2015-10-07T17:50:01Z", - "url": "https://chat.twilio.com/v1/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v1.credentials.create(type="gcm") - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v1/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Test slow create", - "type": "apn", - "sandbox": "False", - "date_created": "2015-10-07T17:50:01Z", - "date_updated": "2015-10-07T17:50:01Z", - "url": "https://chat.twilio.com/v1/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v1.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v1/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Test slow create", - "type": "apn", - "sandbox": "False", - "date_created": "2015-10-07T17:50:01Z", - "date_updated": "2015-10-07T17:50:01Z", - "url": "https://chat.twilio.com/v1/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v1.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://ip-messaging.twilio.com/v1/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.ip_messaging.v1.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/ip_messaging/v1/test_service.py b/tests/integration/ip_messaging/v1/test_service.py deleted file mode 100644 index 0d4bfa71b5..0000000000 --- a/tests/integration/ip_messaging/v1/test_service.py +++ /dev/null @@ -1,279 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ServiceTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "consumption_report_interval": 100, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "default_channel_creator_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_channel_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_service_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "limits": { - "actions_per_second": 20, - "channel_members": 100, - "user_channels": 250 - }, - "links": {}, - "notifications": {}, - "post_webhook_url": "post_webhook_url", - "pre_webhook_url": "pre_webhook_url", - "reachability_enabled": false, - "read_status_enabled": false, - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "typing_indicator_timeout": 100, - "url": "http://www.example.com", - "webhook_filters": [ - "webhook_filters" - ], - "webhook_method": "webhook_method", - "webhooks": {} - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services.create(friendly_name="friendly_name") - - values = {'FriendlyName': "friendly_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v1/Services', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "consumption_report_interval": 100, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "default_channel_creator_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_channel_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_service_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "limits": { - "actions_per_second": 20, - "channel_members": 100, - "user_channels": 250 - }, - "links": {}, - "notifications": {}, - "post_webhook_url": "post_webhook_url", - "pre_webhook_url": "pre_webhook_url", - "reachability_enabled": false, - "read_status_enabled": false, - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "typing_indicator_timeout": 100, - "url": "http://www.example.com", - "webhook_filters": [ - "webhook_filters" - ], - "webhook_method": "webhook_method", - "webhooks": {} - } - ''' - )) - - actual = self.client.ip_messaging.v1.services.create(friendly_name="friendly_name") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v1/Services', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://chat.twilio.com/v1/Services?Page=0&PageSize=50", - "key": "services", - "next_page_url": null, - "page": 0, - "page_size": 0, - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services" - }, - "services": [] - } - ''' - )) - - actual = self.client.ip_messaging.v1.services.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://chat.twilio.com/v1/Services?Page=0&PageSize=50", - "key": "services", - "next_page_url": null, - "page": 0, - "page_size": 1, - "previous_page_url": null, - "url": "https://chat.twilio.com/v1/Services" - }, - "services": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "consumption_report_interval": 100, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "default_channel_creator_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_channel_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_service_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "limits": { - "actions_per_second": 20, - "channel_members": 100, - "user_channels": 250 - }, - "links": {}, - "notifications": {}, - "post_webhook_url": "post_webhook_url", - "pre_webhook_url": "pre_webhook_url", - "reachability_enabled": false, - "read_status_enabled": false, - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "typing_indicator_timeout": 100, - "url": "http://www.example.com", - "webhook_filters": [ - "webhook_filters" - ], - "webhook_method": "webhook_method", - "webhooks": {} - } - ] - } - ''' - )) - - actual = self.client.ip_messaging.v1.services.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "consumption_report_interval": 100, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "default_channel_creator_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_channel_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_service_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "limits": { - "actions_per_second": 20, - "channel_members": 500, - "user_channels": 600 - }, - "links": {}, - "notifications": {}, - "post_webhook_url": "post_webhook_url", - "pre_webhook_url": "pre_webhook_url", - "reachability_enabled": false, - "read_status_enabled": false, - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "typing_indicator_timeout": 100, - "url": "http://www.example.com", - "webhook_filters": [ - "webhook_filters" - ], - "webhook_method": "webhook_method", - "webhooks": {} - } - ''' - )) - - actual = self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/ip_messaging/v2/__init__.py b/tests/integration/ip_messaging/v2/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/ip_messaging/v2/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/ip_messaging/v2/service/__init__.py b/tests/integration/ip_messaging/v2/service/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/ip_messaging/v2/service/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/ip_messaging/v2/service/channel/__init__.py b/tests/integration/ip_messaging/v2/service/channel/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/ip_messaging/v2/service/channel/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/ip_messaging/v2/service/channel/test_invite.py b/tests/integration/ip_messaging/v2/service/channel/test_invite.py deleted file mode 100644 index 89216d71f9..0000000000 --- a/tests/integration/ip_messaging/v2/service/channel/test_invite.py +++ /dev/null @@ -1,195 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class InviteTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites(sid="INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Invites/INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "identity": "identity", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites/INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites(sid="INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites.create(identity="identity") - - values = {'Identity': "identity", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Invites', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "identity": "identity", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites/INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites.create(identity="identity") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Invites', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "invites": [], - "meta": { - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0", - "key": "invites", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "invites": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "identity": "identity", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites/INaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0", - "key": "invites", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites.list() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites(sid="INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Invites/INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites(sid="INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/ip_messaging/v2/service/channel/test_member.py b/tests/integration/ip_messaging/v2/service/channel/test_member.py deleted file mode 100644 index 8cc82a45f3..0000000000 --- a/tests/integration/ip_messaging/v2/service/channel/test_member.py +++ /dev/null @@ -1,237 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class MemberTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members/MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "last_consumed_message_index": null, - "last_consumption_timestamp": null, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members.create(identity="identity") - - values = {'Identity': "identity", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "last_consumed_message_index": null, - "last_consumption_timestamp": null, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members.create(identity="identity") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0", - "next_page_url": null, - "key": "members" - }, - "members": [ - { - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "last_consumed_message_index": null, - "last_consumption_timestamp": null, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0", - "next_page_url": null, - "key": "members" - }, - "members": [] - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members.list() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members/MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members/MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_role_sid_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "last_consumed_message_index": 20, - "last_consumption_timestamp": "2016-03-24T21:05:52Z", - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:51Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members(sid="MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/ip_messaging/v2/service/channel/test_message.py b/tests/integration/ip_messaging/v2/service/channel/test_message.py deleted file mode 100644 index 5a8ba00815..0000000000 --- a/tests/integration/ip_messaging/v2/service/channel/test_message.py +++ /dev/null @@ -1,380 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class MessageTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "last_updated_by": null, - "was_edited": false, - "from": "system", - "attributes": "{}", - "body": "Hello", - "index": 0, - "type": "text", - "media": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_fetch_media_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "last_updated_by": null, - "was_edited": false, - "from": "system", - "attributes": "{}", - "body": "Hello", - "index": 0, - "type": "media", - "media": { - "sid": "MEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "size": 99999999999999, - "content_type": "application/pdf", - "filename": "hello.pdf" - }, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "attributes": null, - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "last_updated_by": "system", - "was_edited": false, - "from": "system", - "body": "Hello", - "index": 0, - "type": "text", - "media": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.create() - - self.assertIsNotNone(actual) - - def test_create_with_all_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:38Z", - "last_updated_by": "username", - "was_edited": true, - "from": "system", - "attributes": "{\\"test\\": \\"test\\"}", - "body": "Hello", - "index": 0, - "type": "text", - "media": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.create() - - self.assertIsNotNone(actual) - - def test_create_media_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "attributes": null, - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "last_updated_by": "system", - "was_edited": false, - "from": "system", - "body": "Hello", - "index": 0, - "type": "text", - "media": { - "sid": "MEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "size": 99999999999999, - "content_type": "application/pdf", - "filename": "hello.pdf" - }, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.create() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages?PageSize=50&Page=0", - "next_page_url": null, - "key": "messages" - }, - "messages": [ - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "last_updated_by": null, - "was_edited": false, - "from": "system", - "attributes": "{}", - "body": "Hello", - "index": 0, - "type": "text", - "media": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "last_updated_by": null, - "was_edited": false, - "from": "system", - "attributes": "{}", - "body": "Hello", - "index": 0, - "type": "media", - "media": { - "sid": "MEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "size": 99999999999999, - "content_type": "application/pdf", - "filename": "hello.pdf" - }, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages?PageSize=50&Page=0", - "next_page_url": null, - "key": "messages" - }, - "messages": [] - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.list() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "attributes": "{ \\"foo\\": \\"bar\\" }", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:38Z", - "last_updated_by": "username", - "was_edited": true, - "from": "system", - "body": "Hello", - "index": 0, - "type": "text", - "media": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages(sid="IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/ip_messaging/v2/service/test_binding.py b/tests/integration/ip_messaging/v2/service/test_binding.py deleted file mode 100644 index 4e1fd2647e..0000000000 --- a/tests/integration/ip_messaging/v2/service/test_binding.py +++ /dev/null @@ -1,165 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class BindingTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings?PageSize=50&Page=0", - "next_page_url": null, - "key": "bindings" - }, - "bindings": [ - { - "sid": "BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-10-21T11:37:03Z", - "date_updated": "2016-10-21T11:37:03Z", - "endpoint": "TestUser-endpoint", - "identity": "TestUser", - "binding_type": "gcm", - "credential_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "message_types": [ - "removed_from_channel", - "new_message", - "added_to_channel", - "invited_to_channel" - ], - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings/BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "user": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/TestUser" - } - } - ] - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings?PageSize=50&Page=0", - "next_page_url": null, - "key": "bindings" - }, - "bindings": [] - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings(sid="BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings/BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-10-21T11:37:03Z", - "date_updated": "2016-10-21T11:37:03Z", - "endpoint": "TestUser-endpoint", - "identity": "TestUser", - "binding_type": "gcm", - "credential_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "message_types": [ - "removed_from_channel", - "new_message", - "added_to_channel", - "invited_to_channel" - ], - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings/BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "user": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/TestUser" - } - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings(sid="BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings(sid="BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings/BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings(sid="BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/ip_messaging/v2/service/test_channel.py b/tests/integration/ip_messaging/v2/service/test_channel.py deleted file mode 100644 index 6ad1d7f832..0000000000 --- a/tests/integration/ip_messaging/v2/service/test_channel.py +++ /dev/null @@ -1,255 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ChannelTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "unique_name": "unique_name", - "attributes": "{ \\"foo\\": \\"bar\\" }", - "type": "public", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:37Z", - "created_by": "system", - "members_count": 0, - "messages_count": 0, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "members": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members", - "messages": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages", - "invites": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites", - "last_message": null - } - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "unique_name": "unique_name", - "attributes": "{ \\"foo\\": \\"bar\\" }", - "type": "public", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:38Z", - "created_by": "username", - "members_count": 0, - "messages_count": 0, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "members": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members", - "messages": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages", - "invites": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites", - "last_message": null - } - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels.create() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "channels": [ - { - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "unique_name": "unique_name", - "attributes": "{ \\"foo\\": \\"bar\\" }", - "type": "public", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:37Z", - "created_by": "system", - "members_count": 0, - "messages_count": 0, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "members": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members", - "messages": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages", - "invites": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites", - "last_message": null - } - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "next_page_url": null, - "key": "channels" - } - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "channels": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "next_page_url": null, - "key": "channels" - } - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "unique_name": "unique_name", - "attributes": "{ \\"foo\\": \\"bar\\" }", - "type": "public", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:38Z", - "created_by": "username", - "members_count": 0, - "messages_count": 0, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "members": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members", - "messages": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages", - "invites": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Invites", - "last_message": null - } - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/ip_messaging/v2/service/test_role.py b/tests/integration/ip_messaging/v2/service/test_role.py deleted file mode 100644 index fb30356c59..0000000000 --- a/tests/integration/ip_messaging/v2/service/test_role.py +++ /dev/null @@ -1,246 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base import serialize -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class RoleTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles(sid="RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Roles/RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "channel user", - "type": "channel", - "permissions": [ - "sendMessage", - "leaveChannel", - "editOwnMessage", - "deleteOwnMessage" - ], - "date_created": "2016-03-03T19:47:15Z", - "date_updated": "2016-03-03T19:47:15Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles(sid="RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles(sid="RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Roles/RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles(sid="RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles.create(friendly_name="friendly_name", type="channel", permission=['permission']) - - values = { - 'FriendlyName': "friendly_name", - 'Type': "channel", - 'Permission': serialize.map(['permission'], lambda e: e), - } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Roles', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "channel user", - "type": "channel", - "permissions": [ - "sendMessage", - "leaveChannel", - "editOwnMessage", - "deleteOwnMessage" - ], - "date_created": "2016-03-03T19:47:15Z", - "date_updated": "2016-03-03T19:47:15Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles.create(friendly_name="friendly_name", type="channel", permission=['permission']) - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Roles', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=50&Page=0", - "next_page_url": null, - "key": "roles" - }, - "roles": [ - { - "sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "channel user", - "type": "channel", - "permissions": [ - "sendMessage", - "leaveChannel", - "editOwnMessage", - "deleteOwnMessage" - ], - "date_created": "2016-03-03T19:47:15Z", - "date_updated": "2016-03-03T19:47:15Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=50&Page=0", - "next_page_url": null, - "key": "roles" - }, - "roles": [] - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles(sid="RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(permission=['permission']) - - values = {'Permission': serialize.map(['permission'], lambda e: e), } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Roles/RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "channel user", - "type": "channel", - "permissions": [ - "sendMessage", - "leaveChannel", - "editOwnMessage", - "deleteOwnMessage" - ], - "date_created": "2016-03-03T19:47:15Z", - "date_updated": "2016-03-03T19:47:15Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles(sid="RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(permission=['permission']) - - self.assertIsNotNone(actual) diff --git a/tests/integration/ip_messaging/v2/service/test_user.py b/tests/integration/ip_messaging/v2/service/test_user.py deleted file mode 100644 index 6affe30184..0000000000 --- a/tests/integration/ip_messaging/v2/service/test_user.py +++ /dev/null @@ -1,250 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class UserTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "attributes": null, - "is_online": true, - "is_notifiable": null, - "friendly_name": null, - "joined_channels_count": 0, - "date_created": "2016-03-24T21:05:19Z", - "date_updated": "2016-03-24T21:05:19Z", - "links": { - "user_channels": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels", - "user_bindings": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings" - }, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.create(identity="identity") - - values = {'Identity': "identity", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "attributes": null, - "is_online": true, - "is_notifiable": null, - "friendly_name": null, - "joined_channels_count": 0, - "date_created": "2016-03-24T21:05:19Z", - "date_updated": "2016-03-24T21:05:19Z", - "links": { - "user_channels": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels", - "user_bindings": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings" - }, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.create(identity="identity") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users?PageSize=50&Page=0", - "next_page_url": null, - "key": "users" - }, - "users": [ - { - "sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "attributes": null, - "is_online": true, - "is_notifiable": null, - "friendly_name": null, - "date_created": "2016-03-24T21:05:19Z", - "date_updated": "2016-03-24T21:05:19Z", - "joined_channels_count": 0, - "links": { - "user_channels": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels", - "user_bindings": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings" - }, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users?PageSize=50&Page=0", - "next_page_url": null, - "key": "users" - }, - "users": [] - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "jing", - "attributes": null, - "is_online": true, - "is_notifiable": null, - "friendly_name": null, - "joined_channels_count": 0, - "date_created": "2016-03-24T21:05:19Z", - "date_updated": "2016-03-24T21:05:19Z", - "links": { - "user_channels": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels", - "user_bindings": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings" - }, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/ip_messaging/v2/service/user/__init__.py b/tests/integration/ip_messaging/v2/service/user/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/ip_messaging/v2/service/user/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/ip_messaging/v2/service/user/test_user_binding.py b/tests/integration/ip_messaging/v2/service/user/test_user_binding.py deleted file mode 100644 index 9324e38060..0000000000 --- a/tests/integration/ip_messaging/v2/service/user/test_user_binding.py +++ /dev/null @@ -1,168 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class UserBindingTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_bindings.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings?PageSize=50&Page=0", - "next_page_url": null, - "key": "bindings" - }, - "bindings": [ - { - "sid": "BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-10-21T11:37:03Z", - "date_updated": "2016-10-21T11:37:03Z", - "endpoint": "TestUser-endpoint", - "identity": "TestUser", - "user_sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "binding_type": "gcm", - "credential_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "message_types": [ - "removed_from_channel", - "new_message", - "added_to_channel", - "invited_to_channel" - ], - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings/BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_bindings.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings?PageSize=50&Page=0", - "next_page_url": null, - "key": "bindings" - }, - "bindings": [] - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_bindings.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_bindings(sid="BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings/BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-10-21T11:37:03Z", - "date_updated": "2016-10-21T11:37:03Z", - "endpoint": "TestUser-endpoint", - "identity": "TestUser", - "user_sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "binding_type": "gcm", - "credential_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "message_types": [ - "removed_from_channel", - "new_message", - "added_to_channel", - "invited_to_channel" - ], - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings/BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_bindings(sid="BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_bindings(sid="BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings/BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_bindings(sid="BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/ip_messaging/v2/service/user/test_user_channel.py b/tests/integration/ip_messaging/v2/service/user/test_user_channel.py deleted file mode 100644 index e3e1262355..0000000000 --- a/tests/integration/ip_messaging/v2/service/user/test_user_channel.py +++ /dev/null @@ -1,92 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class UserChannelTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "next_page_url": null, - "key": "channels" - }, - "channels": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "member_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "joined", - "last_consumed_message_index": 5, - "unread_messages_count": 5, - "links": { - "channel": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "member": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - } - ] - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "next_page_url": null, - "key": "channels" - }, - "channels": [] - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(sid="USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/ip_messaging/v2/test_credential.py b/tests/integration/ip_messaging/v2/test_credential.py deleted file mode 100644 index 0f489d8f95..0000000000 --- a/tests/integration/ip_messaging/v2/test_credential.py +++ /dev/null @@ -1,203 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class CredentialTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.credentials.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v2/Credentials', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "credentials": [ - { - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Test slow create", - "type": "apn", - "sandbox": "False", - "date_created": "2015-10-07T17:50:01Z", - "date_updated": "2015-10-07T17:50:01Z", - "url": "https://chat.twilio.com/v2/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "page": 0, - "page_size": 1, - "first_page_url": "https://chat.twilio.com/v2/Credentials?PageSize=1&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Credentials?PageSize=1&Page=0", - "next_page_url": null, - "key": "credentials" - } - } - ''' - )) - - actual = self.client.ip_messaging.v2.credentials.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "credentials": [], - "meta": { - "page": 0, - "page_size": 1, - "first_page_url": "https://chat.twilio.com/v2/Credentials?PageSize=1&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Credentials?PageSize=1&Page=0", - "next_page_url": null, - "key": "credentials" - } - } - ''' - )) - - actual = self.client.ip_messaging.v2.credentials.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.credentials.create(type="gcm") - - values = {'Type': "gcm", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v2/Credentials', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Test slow create", - "type": "apn", - "sandbox": "False", - "date_created": "2015-10-07T17:50:01Z", - "date_updated": "2015-10-07T17:50:01Z", - "url": "https://chat.twilio.com/v2/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.credentials.create(type="gcm") - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v2/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Test slow create", - "type": "apn", - "sandbox": "False", - "date_created": "2015-10-07T17:50:01Z", - "date_updated": "2015-10-07T17:50:01Z", - "url": "https://chat.twilio.com/v2/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v2/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Test slow create", - "type": "apn", - "sandbox": "False", - "date_created": "2015-10-07T17:50:01Z", - "date_updated": "2015-10-07T17:50:01Z", - "url": "https://chat.twilio.com/v2/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://ip-messaging.twilio.com/v2/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.ip_messaging.v2.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/ip_messaging/v2/test_service.py b/tests/integration/ip_messaging/v2/test_service.py deleted file mode 100644 index cb5028ff7a..0000000000 --- a/tests/integration/ip_messaging/v2/test_service.py +++ /dev/null @@ -1,334 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ServiceTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "consumption_report_interval": 100, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "default_channel_creator_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_channel_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_service_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "limits": { - "channel_members": 100, - "user_channels": 250 - }, - "links": { - "channels": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels", - "users": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users", - "roles": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles", - "bindings": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings" - }, - "notifications": {}, - "post_webhook_url": "post_webhook_url", - "pre_webhook_url": "pre_webhook_url", - "pre_webhook_retry_count": 2, - "post_webhook_retry_count": 3, - "reachability_enabled": false, - "read_status_enabled": false, - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "typing_indicator_timeout": 100, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "webhook_filters": [ - "webhook_filters" - ], - "webhook_method": "webhook_method", - "media": { - "size_limit_mb": 150, - "compatibility_message": "media compatibility message" - } - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services.create(friendly_name="friendly_name") - - values = {'FriendlyName': "friendly_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v2/Services', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "consumption_report_interval": 100, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "default_channel_creator_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_channel_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_service_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "limits": { - "channel_members": 100, - "user_channels": 250 - }, - "links": { - "channels": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels", - "users": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users", - "roles": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles", - "bindings": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings" - }, - "notifications": {}, - "post_webhook_url": "post_webhook_url", - "pre_webhook_url": "pre_webhook_url", - "pre_webhook_retry_count": 2, - "post_webhook_retry_count": 3, - "reachability_enabled": false, - "read_status_enabled": false, - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "typing_indicator_timeout": 100, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "webhook_filters": [ - "webhook_filters" - ], - "webhook_method": "webhook_method", - "media": { - "size_limit_mb": 150, - "compatibility_message": "media compatibility message" - } - } - ''' - )) - - actual = self.client.ip_messaging.v2.services.create(friendly_name="friendly_name") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://ip-messaging.twilio.com/v2/Services', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://chat.twilio.com/v2/Services?PageSize=50&Page=0", - "key": "services", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services?PageSize=50&Page=0" - }, - "services": [] - } - ''' - )) - - actual = self.client.ip_messaging.v2.services.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://chat.twilio.com/v2/Services?PageSize=50&Page=0", - "key": "services", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services?PageSize=50&Page=0" - }, - "services": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "consumption_report_interval": 100, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "default_channel_creator_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_channel_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_service_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "limits": { - "channel_members": 100, - "user_channels": 250 - }, - "links": { - "channels": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels", - "users": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users", - "roles": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles", - "bindings": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings" - }, - "notifications": {}, - "post_webhook_url": "post_webhook_url", - "pre_webhook_url": "pre_webhook_url", - "pre_webhook_retry_count": 2, - "post_webhook_retry_count": 3, - "reachability_enabled": false, - "read_status_enabled": false, - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "typing_indicator_timeout": 100, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "webhook_filters": [ - "webhook_filters" - ], - "webhook_method": "webhook_method", - "media": { - "size_limit_mb": 150, - "compatibility_message": "media compatibility message" - } - } - ] - } - ''' - )) - - actual = self.client.ip_messaging.v2.services.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://ip-messaging.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "consumption_report_interval": 100, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "default_channel_creator_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_channel_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_service_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "limits": { - "channel_members": 500, - "user_channels": 600 - }, - "links": { - "channels": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels", - "users": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users", - "roles": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles", - "bindings": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings" - }, - "notifications": { - "log_enabled": true, - "added_to_channel": { - "enabled": false, - "template": "notifications.added_to_channel.template" - }, - "invited_to_channel": { - "enabled": false, - "template": "notifications.invited_to_channel.template" - }, - "new_message": { - "enabled": false, - "template": "notifications.new_message.template", - "badge_count_enabled": true - }, - "removed_from_channel": { - "enabled": false, - "template": "notifications.removed_from_channel.template" - } - }, - "post_webhook_url": "post_webhook_url", - "pre_webhook_url": "pre_webhook_url", - "pre_webhook_retry_count": 2, - "post_webhook_retry_count": 3, - "reachability_enabled": false, - "read_status_enabled": false, - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "typing_indicator_timeout": 100, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "webhook_filters": [ - "webhook_filters" - ], - "webhook_method": "webhook_method", - "media": { - "size_limit_mb": 150, - "compatibility_message": "new media compatibility message" - } - } - ''' - )) - - actual = self.client.ip_messaging.v2.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/lookups/__init__.py b/tests/integration/lookups/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/lookups/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/lookups/v1/__init__.py b/tests/integration/lookups/v1/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/lookups/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/lookups/v1/test_phone_number.py b/tests/integration/lookups/v1/test_phone_number.py deleted file mode 100644 index 29906009ab..0000000000 --- a/tests/integration/lookups/v1/test_phone_number.py +++ /dev/null @@ -1,61 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class PhoneNumberTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.lookups.v1.phone_numbers(phone_number="+15017122661").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://lookups.twilio.com/v1/PhoneNumbers/+15017122661', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "caller_name": { - "caller_name": "Delicious Cheese Cake", - "caller_type": "CONSUMER", - "error_code": null - }, - "carrier": { - "error_code": null, - "mobile_country_code": "310", - "mobile_network_code": "456", - "name": "verizon", - "type": "mobile" - }, - "country_code": "US", - "national_format": "(510) 867-5309", - "phone_number": "+15108675309", - "add_ons": { - "status": "successful", - "message": null, - "code": null, - "results": {} - }, - "url": "https://lookups.twilio.com/v1/PhoneNumbers/phone_number" - } - ''' - )) - - actual = self.client.lookups.v1.phone_numbers(phone_number="+15017122661").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/messaging/__init__.py b/tests/integration/messaging/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/messaging/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/messaging/v1/__init__.py b/tests/integration/messaging/v1/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/messaging/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/messaging/v1/service/__init__.py b/tests/integration/messaging/v1/service/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/messaging/v1/service/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/messaging/v1/service/test_alpha_sender.py b/tests/integration/messaging/v1/service/test_alpha_sender.py deleted file mode 100644 index 469748d5b2..0000000000 --- a/tests/integration/messaging/v1/service/test_alpha_sender.py +++ /dev/null @@ -1,156 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class AlphaSenderTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .alpha_senders.create(alpha_sender="alpha_sender") - - values = {'AlphaSender': "alpha_sender", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://messaging.twilio.com/v1/Services/MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AlphaSenders', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "AIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:12:31Z", - "date_updated": "2015-07-30T20:12:33Z", - "alpha_sender": "Twilio", - "capabilities": [], - "url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AlphaSenders/AIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .alpha_senders.create(alpha_sender="alpha_sender") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .alpha_senders.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://messaging.twilio.com/v1/Services/MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AlphaSenders', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AlphaSenders?PageSize=50&Page=0", - "previous_page_url": null, - "next_page_url": null, - "key": "alpha_senders", - "url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AlphaSenders?PageSize=50&Page=0" - }, - "alpha_senders": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "AIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:12:31Z", - "date_updated": "2015-07-30T20:12:33Z", - "alpha_sender": "Twilio", - "capabilities": [], - "url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AlphaSenders/AIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .alpha_senders.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .alpha_senders(sid="AIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://messaging.twilio.com/v1/Services/MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AlphaSenders/AIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "AIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:12:31Z", - "date_updated": "2015-07-30T20:12:33Z", - "alpha_sender": "Twilio", - "capabilities": [], - "url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AlphaSenders/AIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .alpha_senders(sid="AIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .alpha_senders(sid="AIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://messaging.twilio.com/v1/Services/MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AlphaSenders/AIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .alpha_senders(sid="AIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/messaging/v1/service/test_phone_number.py b/tests/integration/messaging/v1/service/test_phone_number.py deleted file mode 100644 index 3227e08544..0000000000 --- a/tests/integration/messaging/v1/service/test_phone_number.py +++ /dev/null @@ -1,186 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class PhoneNumberTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers.create(phone_number_sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = {'PhoneNumberSid': "PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://messaging.twilio.com/v1/Services/MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/PhoneNumbers', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:12:31Z", - "date_updated": "2015-07-30T20:12:33Z", - "phone_number": "+987654321", - "country_code": "US", - "capabilities": [], - "url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers.create(phone_number_sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) - - def test_create_with_capabilities_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:12:31Z", - "date_updated": "2015-07-30T20:12:33Z", - "phone_number": "+987654321", - "country_code": "US", - "capabilities": [ - "MMS", - "SMS", - "Voice" - ], - "url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers.create(phone_number_sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://messaging.twilio.com/v1/Services/MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/PhoneNumbers/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://messaging.twilio.com/v1/Services/MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/PhoneNumbers', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers?PageSize=50&Page=0", - "previous_page_url": null, - "next_page_url": null, - "key": "phone_numbers", - "url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers?PageSize=50&Page=0" - }, - "phone_numbers": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:12:31Z", - "date_updated": "2015-07-30T20:12:33Z", - "phone_number": "+987654321", - "country_code": "US", - "capabilities": [], - "url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://messaging.twilio.com/v1/Services/MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/PhoneNumbers/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:12:31Z", - "date_updated": "2015-07-30T20:12:33Z", - "phone_number": "12345", - "country_code": "US", - "capabilities": [], - "url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers/SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/messaging/v1/service/test_short_code.py b/tests/integration/messaging/v1/service/test_short_code.py deleted file mode 100644 index 61bc81b6c8..0000000000 --- a/tests/integration/messaging/v1/service/test_short_code.py +++ /dev/null @@ -1,159 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ShortCodeTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes.create(short_code_sid="SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = {'ShortCodeSid': "SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://messaging.twilio.com/v1/Services/MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ShortCodes', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:12:31Z", - "date_updated": "2015-07-30T20:12:33Z", - "short_code": "12345", - "country_code": "US", - "capabilities": [], - "url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes/SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes.create(short_code_sid="SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes(sid="SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://messaging.twilio.com/v1/Services/MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ShortCodes/SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes(sid="SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://messaging.twilio.com/v1/Services/MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ShortCodes', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes?PageSize=50&Page=0", - "previous_page_url": null, - "next_page_url": null, - "key": "short_codes", - "url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes?PageSize=50&Page=0" - }, - "short_codes": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:12:31Z", - "date_updated": "2015-07-30T20:12:33Z", - "short_code": "12345", - "country_code": "US", - "capabilities": [], - "url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes/SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes(sid="SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://messaging.twilio.com/v1/Services/MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ShortCodes/SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:12:31Z", - "date_updated": "2015-07-30T20:12:33Z", - "short_code": "12345", - "country_code": "US", - "capabilities": [], - "url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes/SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes(sid="SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/messaging/v1/test_service.py b/tests/integration/messaging/v1/test_service.py deleted file mode 100644 index e9c24c8d80..0000000000 --- a/tests/integration/messaging/v1/test_service.py +++ /dev/null @@ -1,244 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ServiceTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.messaging.v1.services.create(friendly_name="friendly_name") - - values = {'FriendlyName': "friendly_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://messaging.twilio.com/v1/Services', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:12:31Z", - "date_updated": "2015-07-30T20:12:33Z", - "friendly_name": "My Service!", - "inbound_request_url": "https://www.example.com/", - "inbound_method": "POST", - "fallback_url": "https://www.example.com", - "fallback_method": "GET", - "status_callback": "https://www.example.com", - "sticky_sender": true, - "smart_encoding": false, - "mms_converter": true, - "fallback_to_long_code": true, - "scan_message_content": "inherit", - "area_code_geomatch": true, - "validity_period": 600, - "synchronous_validation": true, - "links": { - "phone_numbers": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers", - "short_codes": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes", - "alpha_senders": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AlphaSenders" - }, - "url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.messaging.v1.services.create(friendly_name="friendly_name") - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://messaging.twilio.com/v1/Services/MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "My Service!", - "sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:12:31Z", - "date_updated": "2015-07-30T20:12:33Z", - "sticky_sender": false, - "mms_converter": true, - "smart_encoding": false, - "fallback_to_long_code": true, - "scan_message_content": "inherit", - "synchronous_validation": true, - "area_code_geomatch": true, - "validity_period": 600, - "inbound_request_url": "https://www.example.com", - "inbound_method": "POST", - "fallback_url": null, - "fallback_method": "POST", - "status_callback": "https://www.example.com", - "links": { - "phone_numbers": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers", - "short_codes": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes", - "alpha_senders": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AlphaSenders" - }, - "url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.messaging.v1.services.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://messaging.twilio.com/v1/Services', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://messaging.twilio.com/v1/Services?PageSize=50&Page=0", - "previous_page_url": null, - "next_page_url": null, - "key": "services", - "url": "https://messaging.twilio.com/v1/Services?PageSize=50&Page=0" - }, - "services": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "My Service!", - "sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:12:31Z", - "date_updated": "2015-07-30T20:12:33Z", - "sticky_sender": true, - "mms_converter": true, - "smart_encoding": false, - "fallback_to_long_code": true, - "area_code_geomatch": true, - "validity_period": 600, - "scan_message_content": "inherit", - "synchronous_validation": true, - "inbound_request_url": "https://www.example.com/", - "inbound_method": "POST", - "fallback_url": null, - "fallback_method": "POST", - "status_callback": "https://www.example.com", - "links": { - "phone_numbers": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers", - "short_codes": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes", - "alpha_senders": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AlphaSenders" - }, - "url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.messaging.v1.services.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://messaging.twilio.com/v1/Services/MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:12:31Z", - "date_updated": "2015-07-30T20:12:33Z", - "friendly_name": "My Service!", - "inbound_request_url": "https://www.example.com/", - "inbound_method": "POST", - "fallback_url": null, - "fallback_method": "POST", - "status_callback": "https://www.example.com", - "sticky_sender": true, - "mms_converter": true, - "smart_encoding": false, - "fallback_to_long_code": true, - "area_code_geomatch": true, - "validity_period": 600, - "scan_message_content": "inherit", - "synchronous_validation": true, - "links": { - "phone_numbers": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers", - "short_codes": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes", - "alpha_senders": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AlphaSenders" - }, - "url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://messaging.twilio.com/v1/Services/MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.messaging.v1.services(sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/monitor/__init__.py b/tests/integration/monitor/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/monitor/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/monitor/v1/__init__.py b/tests/integration/monitor/v1/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/monitor/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/monitor/v1/test_alert.py b/tests/integration/monitor/v1/test_alert.py deleted file mode 100644 index 6f3e1bffc5..0000000000 --- a/tests/integration/monitor/v1/test_alert.py +++ /dev/null @@ -1,151 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class AlertTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.monitor.v1.alerts(sid="NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://monitor.twilio.com/v1/Alerts/NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "alert_text": "alert_text", - "api_version": "2010-04-01", - "date_created": "2015-07-30T20:00:00Z", - "date_generated": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "error_code": "error_code", - "log_level": "log_level", - "more_info": "more_info", - "request_method": "GET", - "request_url": "http://www.example.com", - "request_variables": "request_variables", - "resource_sid": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "response_body": "response_body", - "response_headers": "response_headers", - "sid": "NOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "http://www.example.com" - } - ''' - )) - - actual = self.client.monitor.v1.alerts(sid="NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.monitor.v1.alerts(sid="NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://monitor.twilio.com/v1/Alerts/NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.monitor.v1.alerts(sid="NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.monitor.v1.alerts.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://monitor.twilio.com/v1/Alerts', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "alerts": [], - "meta": { - "first_page_url": "https://monitor.twilio.com/v1/Alerts?Page=0&PageSize=50", - "key": "alerts", - "next_page_url": null, - "page": 0, - "page_size": 0, - "previous_page_url": null, - "url": "https://monitor.twilio.com/v1/Alerts" - } - } - ''' - )) - - actual = self.client.monitor.v1.alerts.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "alerts": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "alert_text": "alert_text", - "api_version": "2010-04-01", - "date_created": "2015-07-30T20:00:00Z", - "date_generated": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "error_code": "error_code", - "log_level": "log_level", - "more_info": "more_info", - "request_method": "GET", - "request_url": "http://www.example.com", - "resource_sid": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "NOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "http://www.example.com" - } - ], - "meta": { - "first_page_url": "https://monitor.twilio.com/v1/Alerts?Page=0&PageSize=50", - "key": "alerts", - "next_page_url": null, - "page": 0, - "page_size": 1, - "previous_page_url": null, - "url": "https://monitor.twilio.com/v1/Alerts" - } - } - ''' - )) - - actual = self.client.monitor.v1.alerts.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/monitor/v1/test_event.py b/tests/integration/monitor/v1/test_event.py deleted file mode 100644 index a1222a6335..0000000000 --- a/tests/integration/monitor/v1/test_event.py +++ /dev/null @@ -1,143 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class EventTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.monitor.v1.events(sid="AEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://monitor.twilio.com/v1/Events/AEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "actor_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "actor_type": "account", - "description": null, - "event_data": { - "friendly_name": { - "previous": "SubAccount Created at 2014-10-03 09:48 am", - "updated": "Mr. Friendly" - } - }, - "event_date": "2014-10-03T16:48:25Z", - "event_type": "account.updated", - "links": { - "actor": "https://api.twilio.com/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "resource": "https://api.twilio.com/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "resource_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "resource_type": "account", - "sid": "AEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "source": "api", - "source_ip_address": "10.86.6.250", - "url": "https://monitor.twilio.com/v1/Events/AEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.monitor.v1.events(sid="AEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.monitor.v1.events.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://monitor.twilio.com/v1/Events', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "events": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "actor_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "actor_type": "account", - "description": null, - "event_data": { - "friendly_name": { - "previous": "SubAccount Created at 2014-10-03 09:48 am", - "updated": "Mr. Friendly" - } - }, - "event_date": "2014-10-03T16:48:25Z", - "event_type": "account.updated", - "links": { - "actor": "https://api.twilio.com/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "resource": "https://api.twilio.com/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "resource_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "resource_type": "account", - "sid": "AEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "source": "api", - "source_ip_address": "10.86.6.250", - "url": "https://monitor.twilio.com/v1/Events/AEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://monitor.twilio.com/v1/Events?PageSize=50&Page=0", - "key": "events", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://monitor.twilio.com/v1/Events?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.monitor.v1.events.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "events": [], - "meta": { - "first_page_url": "https://monitor.twilio.com/v1/Events?PageSize=50&Page=0", - "key": "events", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://monitor.twilio.com/v1/Events?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.monitor.v1.events.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/notify/__init__.py b/tests/integration/notify/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/notify/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/notify/v1/__init__.py b/tests/integration/notify/v1/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/notify/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/notify/v1/service/__init__.py b/tests/integration/notify/v1/service/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/notify/v1/service/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/notify/v1/service/test_binding.py b/tests/integration/notify/v1/service/test_binding.py deleted file mode 100644 index 133041d98b..0000000000 --- a/tests/integration/notify/v1/service/test_binding.py +++ /dev/null @@ -1,210 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class BindingTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings(sid="BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings/BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "address": "a7c658f4111ec4ff5a1a647f9d0edd819025b9f20522d2fae897049f32873e73", - "binding_type": "apn", - "credential_sid": null, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "endpoint": "26607274", - "identity": "24987039", - "notification_protocol_version": "3", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "tags": [ - "26607274" - ], - "links": { - "user": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/24987039" - }, - "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings/BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings(sid="BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings(sid="BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings/BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings(sid="BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings.create(identity="identity", binding_type="apn", address="address") - - values = {'Identity': "identity", 'BindingType': "apn", 'Address': "address", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "address": "a7c658f4111ec4ff5a1a647f9d0edd819025b9f20522d2fae897049f32873e73", - "binding_type": "apn", - "credential_sid": null, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "endpoint": "26607274", - "identity": "24987039", - "notification_protocol_version": "3", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "tags": [ - "26607274" - ], - "links": { - "user": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/24987039" - }, - "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings/BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings.create(identity="identity", binding_type="apn", address="address") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "bindings": [], - "meta": { - "first_page_url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings?PageSize=50&Page=0", - "key": "bindings", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "bindings": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "address": "a7c658f4111ec4ff5a1a647f9d0edd819025b9f20522d2fae897049f32873e73", - "binding_type": "apn", - "credential_sid": null, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "endpoint": "26607274", - "identity": "24987039", - "notification_protocol_version": "3", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "tags": [ - "26607274" - ], - "links": { - "user": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/24987039" - }, - "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings/BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings?PageSize=50&Page=0", - "key": "bindings", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/notify/v1/service/test_notification.py b/tests/integration/notify/v1/service/test_notification.py deleted file mode 100644 index 446d238a7e..0000000000 --- a/tests/integration/notify/v1/service/test_notification.py +++ /dev/null @@ -1,97 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class NotificationTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .notifications.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Notifications', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "NOb8021351170b4e1286adaac3fdd6d082", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "IS699b53e02da45a1ba9d13b7d7d2766af", - "date_created": "2016-03-24T23:42:28Z", - "identities": [ - "jing" - ], - "tags": [], - "segments": [], - "priority": "high", - "ttl": 2419200, - "title": "test", - "body": "body", - "sound": null, - "action": null, - "data": null, - "apn": null, - "fcm": null, - "gcm": null, - "sms": null, - "facebook_messenger": null, - "alexa": null - } - ''' - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .notifications.create() - - self.assertIsNotNone(actual) - - def test_create_direct_notification_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "NOb8021351170b4e1286adaac3fdd6d082", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "IS699b53e02da45a1ba9d13b7d7d2766af", - "date_created": "2016-03-24T23:42:28Z", - "identities": [], - "tags": [], - "segments": [], - "priority": "high", - "ttl": 2419200, - "title": null, - "body": "body", - "sound": null, - "action": null, - "data": null, - "apn": null, - "fcm": null, - "gcm": null, - "sms": null, - "facebook_messenger": null, - "alexa": null - } - ''' - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .notifications.create() - - self.assertIsNotNone(actual) diff --git a/tests/integration/notify/v1/service/test_segment.py b/tests/integration/notify/v1/service/test_segment.py deleted file mode 100644 index 496e4a4efa..0000000000 --- a/tests/integration/notify/v1/service/test_segment.py +++ /dev/null @@ -1,84 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class SegmentTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .segments.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Segments', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Segments?PageSize=50&Page=0", - "key": "segments", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Segments?PageSize=50&Page=0" - }, - "segments": [] - } - ''' - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .segments.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "segments": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2017-02-14T14:36:41Z", - "date_updated": "2017-02-14T14:36:41Z", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "GSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "segment" - } - ], - "meta": { - "first_page_url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Segments?PageSize=50&Page=0", - "key": "segments", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Segments?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .segments.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/notify/v1/service/test_user.py b/tests/integration/notify/v1/service/test_user.py deleted file mode 100644 index 5922ddfaf3..0000000000 --- a/tests/integration/notify/v1/service/test_user.py +++ /dev/null @@ -1,198 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class UserTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.create(identity="identity") - - values = {'Identity': "identity", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2017-02-17T07:17:02Z", - "date_updated": "2017-02-17T07:17:02Z", - "identity": "identity", - "links": { - "bindings": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/identity/Bindings", - "segment_memberships": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/identity/SegmentMemberships" - }, - "segments": [ - "segment1" - ], - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/identity" - } - ''' - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.create(identity="identity") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(identity="NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(identity="NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(identity="NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2017-02-17T07:17:02Z", - "date_updated": "2017-02-17T07:17:02Z", - "identity": "identity", - "links": { - "bindings": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/identity/Bindings", - "segment_memberships": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/identity/SegmentMemberships" - }, - "segments": [ - "segment1" - ], - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/identity" - } - ''' - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(identity="NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "users": [], - "meta": { - "first_page_url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users?PageSize=50&Page=0", - "key": "users", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "users": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2017-02-17T07:17:02Z", - "date_updated": "2017-02-17T07:17:02Z", - "identity": "identity", - "links": { - "bindings": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/identity/Bindings", - "segment_memberships": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/identity/SegmentMemberships" - }, - "segments": [ - "segment1" - ], - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/identity" - } - ], - "meta": { - "first_page_url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users?PageSize=50&Page=0", - "key": "users", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/notify/v1/service/user/__init__.py b/tests/integration/notify/v1/service/user/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/notify/v1/service/user/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/notify/v1/service/user/test_segment_memberships.py b/tests/integration/notify/v1/service/user/test_segment_memberships.py deleted file mode 100644 index a228ab610a..0000000000 --- a/tests/integration/notify/v1/service/user/test_segment_memberships.py +++ /dev/null @@ -1,109 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class SegmentMembershipTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(identity="NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .segment_memberships.create(segment="segment") - - values = {'Segment': "segment", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SegmentMemberships', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "identity", - "segment": "segment", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/identity/SegmentMemberships/segment" - } - ''' - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(identity="NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .segment_memberships.create(segment="segment") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(identity="NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .segment_memberships(segment="segment").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SegmentMemberships/segment', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(identity="NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .segment_memberships(segment="segment").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(identity="NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .segment_memberships(segment="segment").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SegmentMemberships/segment', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "identity", - "segment": "segment", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/identity/SegmentMemberships/segment" - } - ''' - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(identity="NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .segment_memberships(segment="segment").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/notify/v1/service/user/test_user_binding.py b/tests/integration/notify/v1/service/user/test_user_binding.py deleted file mode 100644 index 3dbd27cdb8..0000000000 --- a/tests/integration/notify/v1/service/user/test_user_binding.py +++ /dev/null @@ -1,252 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class UserBindingTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(identity="NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings(sid="BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings/BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "address": "address", - "binding_type": "binding_type", - "credential_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "endpoint": "endpoint", - "links": { - "user": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/identity" - }, - "identity": "identity", - "notification_protocol_version": "notification_protocol_version", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "tags": [ - "tag" - ], - "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/identity/Bindings/BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(identity="NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings(sid="BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(identity="NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings(sid="BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings/BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(identity="NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings(sid="BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(identity="NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings.create(binding_type="apn", address="address") - - values = {'BindingType': "apn", 'Address': "address", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "address": "address", - "binding_type": "binding_type", - "credential_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "endpoint": "endpoint", - "identity": "identity", - "links": { - "user": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/identity" - }, - "notification_protocol_version": "notification_protocol_version", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "tags": [ - "tag" - ], - "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/identity/Bindings/BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(identity="NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings.create(binding_type="apn", address="address") - - self.assertIsNotNone(actual) - - def test_create_alexa_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "address": "address", - "binding_type": "binding_type", - "credential_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "endpoint": "endpoint", - "identity": "identity", - "links": { - "user": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/identity" - }, - "notification_protocol_version": "notification_protocol_version", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "tags": [ - "tag" - ], - "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/identity/Bindings/BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(identity="NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings.create(binding_type="apn", address="address") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(identity="NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "bindings": [], - "meta": { - "first_page_url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/identity/Bindings?PageSize=50&Page=0", - "key": "bindings", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/identity/Bindings?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(identity="NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "bindings": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "address": "address", - "binding_type": "binding_type", - "credential_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "endpoint": "endpoint", - "identity": "identity", - "links": { - "user": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/identity" - }, - "notification_protocol_version": "notification_protocol_version", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "tags": [ - "tag" - ], - "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/identity/Bindings/BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/identity/Bindings?PageSize=50&Page=0", - "key": "bindings", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/identity/Bindings?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users(identity="NUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/notify/v1/test_credential.py b/tests/integration/notify/v1/test_credential.py deleted file mode 100644 index d57f7a828b..0000000000 --- a/tests/integration/notify/v1/test_credential.py +++ /dev/null @@ -1,203 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class CredentialTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.credentials.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://notify.twilio.com/v1/Credentials', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "credentials": [ - { - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Test slow create", - "type": "apn", - "sandbox": "False", - "date_created": "2015-10-07T17:50:01Z", - "date_updated": "2015-10-07T17:50:01Z", - "url": "https://notify.twilio.com/v1/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "page": 0, - "page_size": 1, - "first_page_url": "https://notify.twilio.com/v1/Credentials?PageSize=1&Page=0", - "previous_page_url": null, - "url": "https://notify.twilio.com/v1/Credentials?PageSize=1&Page=0", - "next_page_url": null, - "key": "credentials" - } - } - ''' - )) - - actual = self.client.notify.v1.credentials.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "credentials": [], - "meta": { - "page": 0, - "page_size": 1, - "first_page_url": "https://notify.twilio.com/v1/Credentials?PageSize=1&Page=0", - "previous_page_url": null, - "url": "https://notify.twilio.com/v1/Credentials?PageSize=1&Page=0", - "next_page_url": null, - "key": "credentials" - } - } - ''' - )) - - actual = self.client.notify.v1.credentials.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.credentials.create(type="gcm") - - values = {'Type': "gcm", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://notify.twilio.com/v1/Credentials', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Test slow create", - "type": "apn", - "sandbox": "False", - "date_created": "2015-10-07T17:50:01Z", - "date_updated": "2015-10-07T17:50:01Z", - "url": "https://notify.twilio.com/v1/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.notify.v1.credentials.create(type="gcm") - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://notify.twilio.com/v1/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Test slow create", - "type": "apn", - "sandbox": "False", - "date_created": "2015-10-07T17:50:01Z", - "date_updated": "2015-10-07T17:50:01Z", - "url": "https://notify.twilio.com/v1/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.notify.v1.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://notify.twilio.com/v1/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Test slow create", - "type": "apn", - "sandbox": "False", - "date_created": "2015-10-07T17:50:01Z", - "date_updated": "2015-10-07T17:50:01Z", - "url": "https://notify.twilio.com/v1/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.notify.v1.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://notify.twilio.com/v1/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.notify.v1.credentials(sid="CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/notify/v1/test_service.py b/tests/integration/notify/v1/test_service.py deleted file mode 100644 index ce24d22df6..0000000000 --- a/tests/integration/notify/v1/test_service.py +++ /dev/null @@ -1,264 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ServiceTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.services.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://notify.twilio.com/v1/Services', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "733c7f0f-6541-42ec-84ce-e2ae1cac588c", - "date_created": "2016-03-09T20:22:31Z", - "date_updated": "2016-03-09T20:22:31Z", - "apn_credential_sid": null, - "gcm_credential_sid": null, - "fcm_credential_sid": null, - "messaging_service_sid": null, - "facebook_messenger_page_id": "4", - "alexa_skill_id": null, - "default_apn_notification_protocol_version": "3", - "default_gcm_notification_protocol_version": "3", - "default_fcm_notification_protocol_version": "3", - "default_alexa_notification_protocol_version": "3", - "log_enabled": true, - "type": "S", - "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "bindings": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings", - "notifications": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications", - "segments": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Segments", - "users": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users" - } - } - ''' - )) - - actual = self.client.notify.v1.services.create() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "733c7f0f-6541-42ec-84ce-e2ae1cac588c", - "date_created": "2016-03-09T20:22:31Z", - "date_updated": "2016-03-09T20:22:31Z", - "apn_credential_sid": null, - "gcm_credential_sid": null, - "fcm_credential_sid": null, - "messaging_service_sid": null, - "facebook_messenger_page_id": "4", - "alexa_skill_id": null, - "default_apn_notification_protocol_version": "3", - "default_gcm_notification_protocol_version": "3", - "default_fcm_notification_protocol_version": "3", - "default_alexa_notification_protocol_version": "3", - "log_enabled": true, - "type": "S", - "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "bindings": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings", - "notifications": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications", - "segments": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Segments", - "users": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users" - } - } - ''' - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.services.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://notify.twilio.com/v1/Services', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://notify.twilio.com/v1/Services?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://notify.twilio.com/v1/Services?PageSize=50&Page=0", - "next_page_url": null, - "key": "services" - }, - "services": [ - { - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "733c7f0f-6541-42ec-84ce-e2ae1cac588c", - "date_created": "2016-03-09T20:22:31Z", - "date_updated": "2016-03-09T20:22:31Z", - "apn_credential_sid": null, - "gcm_credential_sid": null, - "fcm_credential_sid": null, - "messaging_service_sid": null, - "facebook_messenger_page_id": "4", - "alexa_skill_id": null, - "default_apn_notification_protocol_version": "3", - "default_gcm_notification_protocol_version": "3", - "default_fcm_notification_protocol_version": "3", - "default_alexa_notification_protocol_version": "3", - "log_enabled": true, - "type": "S", - "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "bindings": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings", - "notifications": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications", - "segments": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Segments", - "users": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users" - } - } - ] - } - ''' - )) - - actual = self.client.notify.v1.services.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://notify.twilio.com/v1/Services?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://notify.twilio.com/v1/Services?PageSize=50&Page=0", - "next_page_url": null, - "key": "services" - }, - "services": [] - } - ''' - )) - - actual = self.client.notify.v1.services.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "733c7f0f-6541-42ec-84ce-e2ae1cac588c", - "date_created": "2016-03-09T20:22:31Z", - "date_updated": "2016-03-09T20:22:31Z", - "apn_credential_sid": null, - "gcm_credential_sid": null, - "fcm_credential_sid": null, - "default_apn_notification_protocol_version": "3", - "default_gcm_notification_protocol_version": "3", - "default_fcm_notification_protocol_version": "3", - "default_alexa_notification_protocol_version": "3", - "messaging_service_sid": null, - "alexa_skill_id": null, - "facebook_messenger_page_id": "4", - "log_enabled": true, - "type": "S", - "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "bindings": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings", - "notifications": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications", - "segments": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Segments", - "users": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users" - } - } - ''' - )) - - actual = self.client.notify.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/__init__.py b/tests/integration/preview/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/acc_security/__init__.py b/tests/integration/preview/acc_security/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/acc_security/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/acc_security/service/__init__.py b/tests/integration/preview/acc_security/service/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/acc_security/service/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/acc_security/service/test_verification.py b/tests/integration/preview/acc_security/service/test_verification.py deleted file mode 100644 index 353f2e1372..0000000000 --- a/tests/integration/preview/acc_security/service/test_verification.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class VerificationTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.acc_security.services(sid="VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .verifications.create(to="to", channel="channel") - - values = {'To': "to", 'Channel': "channel", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Verification/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Verifications', - data=values, - )) - - def test_create_verification_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "VEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "+14159373912", - "channel": "sms", - "status": "pending", - "valid": null, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z" - } - ''' - )) - - actual = self.client.preview.acc_security.services(sid="VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .verifications.create(to="to", channel="channel") - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/acc_security/service/test_verification_check.py b/tests/integration/preview/acc_security/service/test_verification_check.py deleted file mode 100644 index 395c18e4fb..0000000000 --- a/tests/integration/preview/acc_security/service/test_verification_check.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class VerificationCheckTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.acc_security.services(sid="VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .verification_checks.create(code="code") - - values = {'Code': "code", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Verification/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/VerificationCheck', - data=values, - )) - - def test_verification_checks_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "VEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "+14159373912", - "channel": "sms", - "status": "approved", - "valid": false, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z" - } - ''' - )) - - actual = self.client.preview.acc_security.services(sid="VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .verification_checks.create(code="code") - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/acc_security/test_service.py b/tests/integration/preview/acc_security/test_service.py deleted file mode 100644 index d61fe224a9..0000000000 --- a/tests/integration/preview/acc_security/test_service.py +++ /dev/null @@ -1,171 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ServiceTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.acc_security.services.create(name="name") - - values = {'Name': "name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Verification/Services', - data=values, - )) - - def test_create_record_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "name": "name", - "code_length": 4, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://preview.twilio.com/Verification/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "verification_checks": "https://preview.twilio.com/Verification/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/VerificationCheck", - "verifications": "https://preview.twilio.com/Verification/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Verifications" - } - } - ''' - )) - - actual = self.client.preview.acc_security.services.create(name="name") - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.acc_security.services(sid="VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Verification/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_record_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "name": "name", - "code_length": 4, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://preview.twilio.com/Verification/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "verification_checks": "https://preview.twilio.com/Verification/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/VerificationCheck", - "verifications": "https://preview.twilio.com/Verification/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Verifications" - } - } - ''' - )) - - actual = self.client.preview.acc_security.services(sid="VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.acc_security.services.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Verification/Services', - )) - - def test_read_all_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://preview.twilio.com/Verification/Services?PageSize=50&Page=0", - "previous_page_url": null, - "next_page_url": null, - "key": "services", - "url": "https://preview.twilio.com/Verification/Services?PageSize=50&Page=0" - }, - "services": [ - { - "sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "name": "name", - "code_length": 4, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://preview.twilio.com/Verification/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "verification_checks": "https://preview.twilio.com/Verification/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/VerificationCheck", - "verifications": "https://preview.twilio.com/Verification/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Verifications" - } - } - ] - } - ''' - )) - - actual = self.client.preview.acc_security.services.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.acc_security.services(sid="VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Verification/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_record_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "name": "name", - "code_length": 4, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://preview.twilio.com/Verification/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "verification_checks": "https://preview.twilio.com/Verification/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/VerificationCheck", - "verifications": "https://preview.twilio.com/Verification/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Verifications" - } - } - ''' - )) - - actual = self.client.preview.acc_security.services(sid="VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/bulk_exports/__init__.py b/tests/integration/preview/bulk_exports/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/bulk_exports/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/bulk_exports/export/__init__.py b/tests/integration/preview/bulk_exports/export/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/bulk_exports/export/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/bulk_exports/export/test_day.py b/tests/integration/preview/bulk_exports/export/test_day.py deleted file mode 100644 index a3617f9067..0000000000 --- a/tests/integration/preview/bulk_exports/export/test_day.py +++ /dev/null @@ -1,57 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class DayTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.bulk_exports.exports(resource_type="resource_type") \ - .days.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/BulkExports/Exports/resource_type/Days', - )) - - def test_read_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "days": [ - { - "day": "2017-05-01", - "size": 1234, - "resource_type": "Calls" - } - ], - "meta": { - "key": "days", - "page_size": 50, - "url": "https://preview.twilio.com/BulkExports/Exports/Calls/Days?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://preview.twilio.com/BulkExports/Exports/Calls/Days?PageSize=50&Page=0", - "previous_page_url": null, - "next_page_url": null - } - } - ''' - )) - - actual = self.client.preview.bulk_exports.exports(resource_type="resource_type") \ - .days.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/bulk_exports/test_export.py b/tests/integration/preview/bulk_exports/test_export.py deleted file mode 100644 index 8f3943c77c..0000000000 --- a/tests/integration/preview/bulk_exports/test_export.py +++ /dev/null @@ -1,44 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ExportTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.bulk_exports.exports(resource_type="resource_type").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/BulkExports/Exports/resource_type', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "resource_type": "Calls", - "url": "https://preview.twilio.com/BulkExports/Exports/Calls", - "links": { - "days": "https://preview.twilio.com/BulkExports/Exports/Calls/Days" - } - } - ''' - )) - - actual = self.client.preview.bulk_exports.exports(resource_type="resource_type").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/bulk_exports/test_export_configuration.py b/tests/integration/preview/bulk_exports/test_export_configuration.py deleted file mode 100644 index e2d3d17c3d..0000000000 --- a/tests/integration/preview/bulk_exports/test_export_configuration.py +++ /dev/null @@ -1,73 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ExportConfigurationTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.bulk_exports.export_configuration(resource_type="resource_type").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/BulkExports/Exports/resource_type/Configuration', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "url": "https://preview.twilio.com/BulkExports/Exports/Calls/Configuration", - "enabled": true, - "webhook_url": "", - "webhook_method": "", - "resource_type": "Calls" - } - ''' - )) - - actual = self.client.preview.bulk_exports.export_configuration(resource_type="resource_type").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.bulk_exports.export_configuration(resource_type="resource_type").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/BulkExports/Exports/resource_type/Configuration', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "url": "https://preview.twilio.com/BulkExports/Exports/Calls/Configuration", - "enabled": true, - "webhook_url": "", - "resource_type": "Calls", - "webhook_method": "" - } - ''' - )) - - actual = self.client.preview.bulk_exports.export_configuration(resource_type="resource_type").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/deployed_devices/__init__.py b/tests/integration/preview/deployed_devices/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/deployed_devices/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/deployed_devices/fleet/__init__.py b/tests/integration/preview/deployed_devices/fleet/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/deployed_devices/fleet/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/deployed_devices/fleet/test_certificate.py b/tests/integration/preview/deployed_devices/fleet/test_certificate.py deleted file mode 100644 index a76f0e9396..0000000000 --- a/tests/integration/preview/deployed_devices/fleet/test_certificate.py +++ /dev/null @@ -1,218 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class CertificateTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .certificates(sid="CYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Certificates/CYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "CYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "fleet_sid": "FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "device_sid": "THaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "thumbprint": "1234567890", - "date_created": "2016-07-30T20:00:00Z", - "date_updated": null, - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Certificates/CYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .certificates(sid="CYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .certificates(sid="CYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Certificates/CYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .certificates(sid="CYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .certificates.create(certificate_data="certificate_data") - - values = {'CertificateData': "certificate_data", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Certificates', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "CYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "fleet_sid": "FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "device_sid": "THaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "thumbprint": "1234567890", - "date_created": "2016-07-30T20:00:00Z", - "date_updated": null, - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Certificates/CYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .certificates.create(certificate_data="certificate_data") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .certificates.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Certificates', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "certificates": [], - "meta": { - "first_page_url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Certificates?PageSize=50&Page=0", - "key": "certificates", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Certificates?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .certificates.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "certificates": [ - { - "sid": "CYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "fleet_sid": "FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "device_sid": "THaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "thumbprint": "1234567890", - "date_created": "2016-07-30T20:00:00Z", - "date_updated": null, - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Certificates/CYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Certificates?PageSize=50&Page=0", - "key": "certificates", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Certificates?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .certificates.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .certificates(sid="CYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Certificates/CYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "CYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "fleet_sid": "FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "device_sid": "THaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "thumbprint": "1234567890", - "date_created": "2016-07-30T20:00:00Z", - "date_updated": "2016-07-30T20:00:00Z", - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Certificates/CYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .certificates(sid="CYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/deployed_devices/fleet/test_deployment.py b/tests/integration/preview/deployed_devices/fleet/test_deployment.py deleted file mode 100644 index 9dc9041bf4..0000000000 --- a/tests/integration/preview/deployed_devices/fleet/test_deployment.py +++ /dev/null @@ -1,211 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class DeploymentTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .deployments(sid="DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Deployments/DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "DLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "fleet_sid": "FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sync_service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-07-30T20:00:00Z", - "date_updated": "2016-07-30T20:00:00Z", - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Deployments/DLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .deployments(sid="DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .deployments(sid="DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Deployments/DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .deployments(sid="DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .deployments.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Deployments', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "DLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "fleet_sid": "FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sync_service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-07-30T20:00:00Z", - "date_updated": "2016-07-30T20:00:00Z", - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Deployments/DLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .deployments.create() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .deployments.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Deployments', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "deployments": [], - "meta": { - "first_page_url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Deployments?PageSize=50&Page=0", - "key": "deployments", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Deployments?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .deployments.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "deployments": [ - { - "sid": "DLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "fleet_sid": "FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sync_service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-07-30T20:00:00Z", - "date_updated": "2016-07-30T20:00:00Z", - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Deployments/DLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Deployments?PageSize=50&Page=0", - "key": "deployments", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Deployments?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .deployments.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .deployments(sid="DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Deployments/DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "DLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "fleet_sid": "FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sync_service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-07-30T20:00:00Z", - "date_updated": "2016-07-30T20:00:00Z", - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Deployments/DLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .deployments(sid="DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/deployed_devices/fleet/test_device.py b/tests/integration/preview/deployed_devices/fleet/test_device.py deleted file mode 100644 index caa92e09d4..0000000000 --- a/tests/integration/preview/deployed_devices/fleet/test_device.py +++ /dev/null @@ -1,227 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class DeviceTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .devices(sid="THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Devices/THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "THaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "fleet_sid": "FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "enabled": true, - "deployment_sid": "DLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "bob@twilio.com", - "date_created": "2016-07-30T20:00:00Z", - "date_updated": "2016-07-30T20:00:00Z", - "date_authenticated": null, - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Devices/THaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .devices(sid="THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .devices(sid="THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Devices/THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .devices(sid="THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .devices.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Devices', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "THaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "fleet_sid": "FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "enabled": true, - "deployment_sid": "DLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "bob@twilio.com", - "date_created": "2016-07-30T20:00:00Z", - "date_updated": "2016-07-30T20:00:00Z", - "date_authenticated": null, - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Devices/THaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .devices.create() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .devices.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Devices', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "devices": [], - "meta": { - "first_page_url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Devices?PageSize=50&Page=0", - "key": "devices", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Devices?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .devices.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "devices": [ - { - "sid": "THaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "enabled": true, - "fleet_sid": "FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "deployment_sid": "DLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "bob@twilio.com", - "date_created": "2016-07-30T20:00:00Z", - "date_updated": "2016-07-30T20:00:00Z", - "date_authenticated": null, - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Devices/THaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Devices?PageSize=50&Page=0", - "key": "devices", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Devices?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .devices.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .devices(sid="THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Devices/THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "THaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "fleet_sid": "FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "enabled": true, - "deployment_sid": "DLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "bob@twilio.com", - "date_created": "2016-07-30T20:00:00Z", - "date_updated": "2016-07-30T20:00:00Z", - "date_authenticated": null, - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Devices/THaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .devices(sid="THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/deployed_devices/fleet/test_key.py b/tests/integration/preview/deployed_devices/fleet/test_key.py deleted file mode 100644 index 7ec4fc3bf4..0000000000 --- a/tests/integration/preview/deployed_devices/fleet/test_key.py +++ /dev/null @@ -1,215 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class KeyTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys(sid="KYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Keys/KYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "KYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "fleet_sid": "FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "device_sid": "THaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "secret": null, - "date_created": "2016-07-30T20:00:00Z", - "date_updated": null, - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Keys/KYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys(sid="KYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys(sid="KYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Keys/KYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys(sid="KYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Keys', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "KYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "fleet_sid": "FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "device_sid": "THaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "secret": null, - "date_created": "2016-07-30T20:00:00Z", - "date_updated": null, - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Keys/KYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys.create() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Keys', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "keys": [], - "meta": { - "first_page_url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Keys?PageSize=50&Page=0", - "key": "keys", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Keys?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "keys": [ - { - "sid": "KYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "fleet_sid": "FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "device_sid": "THaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "secret": null, - "date_created": "2016-07-30T20:00:00Z", - "date_updated": "2016-07-30T20:00:00Z", - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Keys/KYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Keys?PageSize=50&Page=0", - "key": "keys", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Keys?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys(sid="KYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Keys/KYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "KYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "fleet_sid": "FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "device_sid": "THaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "secret": null, - "date_created": "2016-07-30T20:00:00Z", - "date_updated": "2016-07-30T20:00:00Z", - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Keys/KYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys(sid="KYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/deployed_devices/test_fleet.py b/tests/integration/preview/deployed_devices/test_fleet.py deleted file mode 100644 index 8cb59f2340..0000000000 --- a/tests/integration/preview/deployed_devices/test_fleet.py +++ /dev/null @@ -1,224 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class FleetTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_deployment_sid": "DLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-07-30T20:00:00Z", - "date_updated": "2016-07-30T20:00:00Z", - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "devices": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Devices", - "deployments": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Deployments", - "certificates": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Certificates", - "keys": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Keys" - } - } - ''' - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.deployed_devices.fleets.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/DeployedDevices/Fleets', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_deployment_sid": "DLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-07-30T20:00:00Z", - "date_updated": null, - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "devices": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Devices", - "deployments": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Deployments", - "certificates": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Certificates", - "keys": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Keys" - } - } - ''' - )) - - actual = self.client.preview.deployed_devices.fleets.create() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.deployed_devices.fleets.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/DeployedDevices/Fleets', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "fleets": [], - "meta": { - "first_page_url": "https://preview.twilio.com/DeployedDevices/Fleets?PageSize=50&Page=0", - "key": "fleets", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/DeployedDevices/Fleets?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.deployed_devices.fleets.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "fleets": [ - { - "sid": "FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_deployment_sid": "DLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-07-30T20:00:00Z", - "date_updated": null, - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "devices": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Devices", - "deployments": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Deployments", - "certificates": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Certificates", - "keys": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Keys" - } - } - ], - "meta": { - "first_page_url": "https://preview.twilio.com/DeployedDevices/Fleets?PageSize=50&Page=0", - "key": "fleets", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/DeployedDevices/Fleets?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.deployed_devices.fleets.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "default_deployment_sid": "DLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-07-30T20:00:00Z", - "date_updated": "2016-07-30T20:00:00Z", - "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "devices": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Devices", - "deployments": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Deployments", - "certificates": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Certificates", - "keys": "https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Keys" - } - } - ''' - )) - - actual = self.client.preview.deployed_devices.fleets(sid="FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/hosted_numbers/__init__.py b/tests/integration/preview/hosted_numbers/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/hosted_numbers/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/hosted_numbers/authorization_document/__init__.py b/tests/integration/preview/hosted_numbers/authorization_document/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/hosted_numbers/authorization_document/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/hosted_numbers/authorization_document/test_dependent_hosted_number_order.py b/tests/integration/preview/hosted_numbers/authorization_document/test_dependent_hosted_number_order.py deleted file mode 100644 index 18fb42c0be..0000000000 --- a/tests/integration/preview/hosted_numbers/authorization_document/test_dependent_hosted_number_order.py +++ /dev/null @@ -1,109 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class DependentHostedNumberOrderTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.hosted_numbers.authorization_documents(sid="PXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .dependent_hosted_number_orders.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/DependentHostedNumberOrders', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DependentHostedNumberOrders?PageSize=50&Page=0", - "key": "items", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DependentHostedNumberOrders?PageSize=50&Page=0" - }, - "items": [] - } - ''' - )) - - actual = self.client.preview.hosted_numbers.authorization_documents(sid="PXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .dependent_hosted_number_orders.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DependentHostedNumberOrders?PageSize=50&Page=0", - "key": "items", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DependentHostedNumberOrders?PageSize=50&Page=0" - }, - "items": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "address_sid": "AD11111111111111111111111111111111", - "call_delay": 15, - "capabilities": { - "sms": true, - "voice": false - }, - "cc_emails": [ - "aaa@twilio.com", - "bbb@twilio.com" - ], - "date_created": "2017-03-28T20:06:39Z", - "date_updated": "2017-03-28T20:06:39Z", - "email": "test@twilio.com", - "extension": "1234", - "friendly_name": "friendly_name", - "incoming_phone_number_sid": "PN11111111111111111111111111111111", - "phone_number": "+14153608311", - "sid": "HRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "signing_document_sid": "PX11111111111111111111111111111111", - "status": "received", - "failure_reason": "", - "unique_name": "foobar", - "verification_attempts": 0, - "verification_call_sids": [ - "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab" - ], - "verification_code": "8794", - "verification_document_sid": null, - "verification_type": "phone-call" - } - ] - } - ''' - )) - - actual = self.client.preview.hosted_numbers.authorization_documents(sid="PXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .dependent_hosted_number_orders.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/hosted_numbers/test_authorization_document.py b/tests/integration/preview/hosted_numbers/test_authorization_document.py deleted file mode 100644 index 5b085c8e57..0000000000 --- a/tests/integration/preview/hosted_numbers/test_authorization_document.py +++ /dev/null @@ -1,211 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base import serialize -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class AuthorizationDocumentTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.hosted_numbers.authorization_documents(sid="PXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "address_sid": "AD11111111111111111111111111111111", - "cc_emails": [ - "aaa@twilio.com", - "bbb@twilio.com" - ], - "date_created": "2017-03-28T20:06:39Z", - "date_updated": "2017-03-28T20:06:39Z", - "email": "test@twilio.com", - "links": { - "dependent_hosted_number_orders": "https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DependentHostedNumberOrders" - }, - "sid": "PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "signing", - "url": "https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.hosted_numbers.authorization_documents(sid="PXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.hosted_numbers.authorization_documents(sid="PXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "address_sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "cc_emails": [ - "test1@twilio.com", - "test2@twilio.com" - ], - "date_created": "2017-03-28T20:06:39Z", - "date_updated": "2017-03-28T20:06:39Z", - "email": "test+hosted@twilio.com", - "links": { - "dependent_hosted_number_orders": "https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DependentHostedNumberOrders" - }, - "sid": "PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "signing", - "url": "https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.hosted_numbers.authorization_documents(sid="PXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.hosted_numbers.authorization_documents.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/HostedNumbers/AuthorizationDocuments', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://preview.twilio.com/HostedNumbers/AuthorizationDocuments?PageSize=50&Page=0", - "key": "items", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/HostedNumbers/AuthorizationDocuments?PageSize=50&Page=0" - }, - "items": [] - } - ''' - )) - - actual = self.client.preview.hosted_numbers.authorization_documents.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://preview.twilio.com/HostedNumbers/AuthorizationDocuments?PageSize=50&Page=0", - "key": "items", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/HostedNumbers/AuthorizationDocuments?PageSize=50&Page=0" - }, - "items": [ - { - "address_sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "cc_emails": [ - "test1@twilio.com", - "test2@twilio.com" - ], - "date_created": "2017-03-28T20:06:39Z", - "date_updated": "2017-03-28T20:06:39Z", - "email": "test+hosted@twilio.com", - "links": { - "dependent_hosted_number_orders": "https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DependentHostedNumberOrders" - }, - "sid": "PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "signing", - "url": "https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.preview.hosted_numbers.authorization_documents.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.hosted_numbers.authorization_documents.create(hosted_number_order_sids=['hosted_number_order_sids'], address_sid="ADXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", email="email") - - values = { - 'HostedNumberOrderSids': serialize.map(['hosted_number_order_sids'], lambda e: e), - 'AddressSid': "ADXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", - 'Email': "email", - } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/HostedNumbers/AuthorizationDocuments', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "address_sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "cc_emails": [ - "test1@twilio.com", - "test2@twilio.com" - ], - "date_created": "2017-03-28T20:06:39Z", - "date_updated": "2017-03-28T20:06:39Z", - "email": "test+hosted@twilio.com", - "links": { - "dependent_hosted_number_orders": "https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DependentHostedNumberOrders" - }, - "sid": "PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "signing", - "url": "https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.hosted_numbers.authorization_documents.create(hosted_number_order_sids=['hosted_number_order_sids'], address_sid="ADXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", email="email") - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/hosted_numbers/test_hosted_number_order.py b/tests/integration/preview/hosted_numbers/test_hosted_number_order.py deleted file mode 100644 index fcda938751..0000000000 --- a/tests/integration/preview/hosted_numbers/test_hosted_number_order.py +++ /dev/null @@ -1,371 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class HostedNumberOrderTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.hosted_numbers.hosted_number_orders(sid="HRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/HostedNumbers/HostedNumberOrders/HRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "address_sid": "AD11111111111111111111111111111111", - "call_delay": 15, - "capabilities": { - "sms": true, - "voice": false - }, - "cc_emails": [ - "aaa@twilio.com", - "bbb@twilio.com" - ], - "date_created": "2017-03-28T20:06:39Z", - "date_updated": "2017-03-28T20:06:39Z", - "email": "test@twilio.com", - "extension": "5105", - "failure_reason": "", - "friendly_name": "friendly_name", - "incoming_phone_number_sid": "PN11111111111111111111111111111111", - "phone_number": "+14153608311", - "sid": "HRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "signing_document_sid": "PX11111111111111111111111111111111", - "status": "received", - "unique_name": "foobar", - "url": "https://preview.twilio.com/HostedNumbers/HostedNumberOrders/HRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "verification_attempts": 0, - "verification_call_sids": [ - "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab" - ], - "verification_code": "8794", - "verification_document_sid": null, - "verification_type": "phone-call" - } - ''' - )) - - actual = self.client.preview.hosted_numbers.hosted_number_orders(sid="HRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.hosted_numbers.hosted_number_orders(sid="HRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/HostedNumbers/HostedNumberOrders/HRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.hosted_numbers.hosted_number_orders(sid="HRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.hosted_numbers.hosted_number_orders(sid="HRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/HostedNumbers/HostedNumberOrders/HRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "address_sid": "AD11111111111111111111111111111111", - "call_delay": 15, - "capabilities": { - "sms": true, - "voice": false - }, - "cc_emails": [ - "test1@twilio.com", - "test2@twilio.com" - ], - "date_created": "2017-03-28T20:06:39Z", - "date_updated": "2017-03-28T20:06:39Z", - "email": "test+hosted@twilio.com", - "extension": "1234", - "failure_reason": "", - "friendly_name": "new friendly name", - "incoming_phone_number_sid": "PN11111111111111111111111111111111", - "phone_number": "+14153608311", - "sid": "HRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "signing_document_sid": "PX11111111111111111111111111111111", - "status": "pending-loa", - "unique_name": "new unique name", - "url": "https://preview.twilio.com/HostedNumbers/HostedNumberOrders/HRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "verification_attempts": 1, - "verification_call_sids": [ - "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab" - ], - "verification_code": "8794", - "verification_document_sid": null, - "verification_type": "phone-call" - } - ''' - )) - - actual = self.client.preview.hosted_numbers.hosted_number_orders(sid="HRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.hosted_numbers.hosted_number_orders.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/HostedNumbers/HostedNumberOrders', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://preview.twilio.com/HostedNumbers/HostedNumberOrders?PageSize=50&Page=0", - "key": "items", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/HostedNumbers/HostedNumberOrders?PageSize=50&Page=0" - }, - "items": [] - } - ''' - )) - - actual = self.client.preview.hosted_numbers.hosted_number_orders.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://preview.twilio.com/HostedNumbers/HostedNumberOrders?PageSize=50&Page=0", - "key": "items", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/HostedNumbers/HostedNumberOrders?PageSize=50&Page=0" - }, - "items": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "address_sid": "AD11111111111111111111111111111111", - "call_delay": 15, - "capabilities": { - "sms": true, - "voice": false - }, - "cc_emails": [ - "aaa@twilio.com", - "bbb@twilio.com" - ], - "date_created": "2017-03-28T20:06:39Z", - "date_updated": "2017-03-28T20:06:39Z", - "email": "test@twilio.com", - "extension": "1234", - "failure_reason": "", - "friendly_name": "friendly_name", - "incoming_phone_number_sid": "PN11111111111111111111111111111111", - "phone_number": "+14153608311", - "sid": "HRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "signing_document_sid": "PX11111111111111111111111111111111", - "status": "received", - "unique_name": "foobar", - "url": "https://preview.twilio.com/HostedNumbers/HostedNumberOrders/HRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "verification_attempts": 0, - "verification_call_sids": [ - "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab" - ], - "verification_code": "8794", - "verification_document_sid": null, - "verification_type": "phone-call" - } - ] - } - ''' - )) - - actual = self.client.preview.hosted_numbers.hosted_number_orders.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.hosted_numbers.hosted_number_orders.create(phone_number="+15017122661", sms_capability=True) - - values = {'PhoneNumber': "+15017122661", 'SmsCapability': True, } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/HostedNumbers/HostedNumberOrders', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "address_sid": "AD11111111111111111111111111111111", - "call_delay": 0, - "capabilities": { - "sms": true, - "voice": false - }, - "cc_emails": [], - "date_created": "2017-03-28T20:06:39Z", - "date_updated": "2017-03-28T20:06:39Z", - "email": "test@twilio.com", - "extension": null, - "failure_reason": "", - "friendly_name": null, - "incoming_phone_number_sid": "PN11111111111111111111111111111111", - "phone_number": "+14153608311", - "sid": "HRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "signing_document_sid": null, - "status": "received", - "unique_name": null, - "url": "https://preview.twilio.com/HostedNumbers/HostedNumberOrders/HRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "verification_attempts": 0, - "verification_call_sids": null, - "verification_code": null, - "verification_document_sid": null, - "verification_type": "phone-call" - } - ''' - )) - - actual = self.client.preview.hosted_numbers.hosted_number_orders.create(phone_number="+15017122661", sms_capability=True) - - self.assertIsNotNone(actual) - - def test_create_without_optional_loa_fields_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "address_sid": null, - "call_delay": 0, - "capabilities": { - "sms": true, - "voice": false - }, - "cc_emails": [], - "date_created": "2017-03-28T20:06:39Z", - "date_updated": "2017-03-28T20:06:39Z", - "email": null, - "extension": null, - "failure_reason": "", - "friendly_name": null, - "incoming_phone_number_sid": "PN11111111111111111111111111111111", - "phone_number": "+14153608311", - "sid": "HRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "signing_document_sid": null, - "status": "received", - "unique_name": null, - "url": "https://preview.twilio.com/HostedNumbers/HostedNumberOrders/HRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "verification_attempts": 0, - "verification_call_sids": null, - "verification_code": null, - "verification_document_sid": null, - "verification_type": "phone-call" - } - ''' - )) - - actual = self.client.preview.hosted_numbers.hosted_number_orders.create(phone_number="+15017122661", sms_capability=True) - - self.assertIsNotNone(actual) - - def test_create_with_phone_bill_verification_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "address_sid": null, - "call_delay": 0, - "capabilities": { - "sms": true, - "voice": false - }, - "cc_emails": [], - "date_created": "2017-03-28T20:06:39Z", - "date_updated": "2017-03-28T20:06:39Z", - "email": null, - "extension": null, - "failure_reason": "", - "friendly_name": null, - "incoming_phone_number_sid": "PN11111111111111111111111111111111", - "phone_number": "+14153608311", - "sid": "HRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "signing_document_sid": null, - "status": "received", - "unique_name": null, - "url": "https://preview.twilio.com/HostedNumbers/HostedNumberOrders/HRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "verification_attempts": 0, - "verification_call_sids": null, - "verification_code": null, - "verification_document_sid": "RIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "verification_type": "phone-bill" - } - ''' - )) - - actual = self.client.preview.hosted_numbers.hosted_number_orders.create(phone_number="+15017122661", sms_capability=True) - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/marketplace/__init__.py b/tests/integration/preview/marketplace/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/marketplace/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/marketplace/available_add_on/__init__.py b/tests/integration/preview/marketplace/available_add_on/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/marketplace/available_add_on/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/marketplace/available_add_on/test_available_add_on_extension.py b/tests/integration/preview/marketplace/available_add_on/test_available_add_on_extension.py deleted file mode 100644 index 5d25589db5..0000000000 --- a/tests/integration/preview/marketplace/available_add_on/test_available_add_on_extension.py +++ /dev/null @@ -1,116 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class AvailableAddOnExtensionTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.marketplace.available_add_ons(sid="XBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .extensions(sid="XFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/marketplace/AvailableAddOns/XBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Extensions/XFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "XFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "available_add_on_sid": "XBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Incoming Voice Call", - "product_name": "Programmable Voice", - "unique_name": "voice-incoming", - "url": "https://preview.twilio.com/marketplace/AvailableAddOns/XBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions/XFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.marketplace.available_add_ons(sid="XBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .extensions(sid="XFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.marketplace.available_add_ons(sid="XBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .extensions.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/marketplace/AvailableAddOns/XBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Extensions', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "extensions": [ - { - "sid": "XFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "available_add_on_sid": "XBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Incoming Voice Call", - "product_name": "Programmable Voice", - "unique_name": "voice-incoming", - "url": "https://preview.twilio.com/marketplace/AvailableAddOns/XBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions/XFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://preview.twilio.com/marketplace/AvailableAddOns/XBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://preview.twilio.com/marketplace/AvailableAddOns/XBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions?PageSize=50&Page=0", - "next_page_url": null, - "key": "extensions" - } - } - ''' - )) - - actual = self.client.preview.marketplace.available_add_ons(sid="XBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .extensions.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "extensions": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://preview.twilio.com/marketplace/AvailableAddOns/XBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://preview.twilio.com/marketplace/AvailableAddOns/XBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions?PageSize=50&Page=0", - "next_page_url": null, - "key": "extensions" - } - } - ''' - )) - - actual = self.client.preview.marketplace.available_add_ons(sid="XBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .extensions.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/marketplace/installed_add_on/__init__.py b/tests/integration/preview/marketplace/installed_add_on/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/marketplace/installed_add_on/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/marketplace/installed_add_on/test_installed_add_on_extension.py b/tests/integration/preview/marketplace/installed_add_on/test_installed_add_on_extension.py deleted file mode 100644 index 61a4f67277..0000000000 --- a/tests/integration/preview/marketplace/installed_add_on/test_installed_add_on_extension.py +++ /dev/null @@ -1,154 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class InstalledAddOnExtensionTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.marketplace.installed_add_ons(sid="XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .extensions(sid="XFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/marketplace/InstalledAddOns/XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Extensions/XFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "XFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "installed_add_on_sid": "XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Incoming Voice Call", - "product_name": "Programmable Voice", - "unique_name": "voice-incoming", - "enabled": true, - "url": "https://preview.twilio.com/marketplace/InstalledAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions/XFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.marketplace.installed_add_ons(sid="XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .extensions(sid="XFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.marketplace.installed_add_ons(sid="XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .extensions(sid="XFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(enabled=True) - - values = {'Enabled': True, } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/marketplace/InstalledAddOns/XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Extensions/XFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "XFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "installed_add_on_sid": "XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Incoming Voice Call", - "product_name": "Programmable Voice", - "unique_name": "voice-incoming", - "enabled": false, - "url": "https://preview.twilio.com/marketplace/InstalledAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions/XFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.marketplace.installed_add_ons(sid="XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .extensions(sid="XFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(enabled=True) - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.marketplace.installed_add_ons(sid="XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .extensions.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/marketplace/InstalledAddOns/XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Extensions', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "extensions": [ - { - "sid": "XFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "installed_add_on_sid": "XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Incoming Voice Call", - "product_name": "Programmable Voice", - "unique_name": "voice-incoming", - "enabled": true, - "url": "https://preview.twilio.com/marketplace/InstalledAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions/XFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://preview.twilio.com/marketplace/InstalledAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://preview.twilio.com/marketplace/InstalledAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions?PageSize=50&Page=0", - "next_page_url": null, - "key": "extensions" - } - } - ''' - )) - - actual = self.client.preview.marketplace.installed_add_ons(sid="XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .extensions.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "extensions": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://preview.twilio.com/marketplace/InstalledAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://preview.twilio.com/marketplace/InstalledAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions?PageSize=50&Page=0", - "next_page_url": null, - "key": "extensions" - } - } - ''' - )) - - actual = self.client.preview.marketplace.installed_add_ons(sid="XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .extensions.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/marketplace/test_available_add_on.py b/tests/integration/preview/marketplace/test_available_add_on.py deleted file mode 100644 index bb7970ae92..0000000000 --- a/tests/integration/preview/marketplace/test_available_add_on.py +++ /dev/null @@ -1,137 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class AvailableAddOnTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.marketplace.available_add_ons(sid="XBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/marketplace/AvailableAddOns/XBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "XBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "VoiceBase High Accuracy Transcription", - "description": "Automatic Transcription and Keyword Extract...", - "pricing_type": "per minute", - "configuration_schema": { - "type": "object", - "properties": { - "bad_words": { - "type": "boolean" - } - }, - "required": [ - "bad_words" - ] - }, - "url": "https://preview.twilio.com/marketplace/AvailableAddOns/XBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "extensions": "https://preview.twilio.com/marketplace/AvailableAddOns/XBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions" - } - } - ''' - )) - - actual = self.client.preview.marketplace.available_add_ons(sid="XBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.marketplace.available_add_ons.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/marketplace/AvailableAddOns', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "available_add_ons": [ - { - "sid": "XBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "VoiceBase High Accuracy Transcription", - "description": "Automatic Transcription and Keyword Extract...", - "pricing_type": "per minute", - "configuration_schema": { - "type": "object", - "properties": { - "bad_words": { - "type": "boolean" - } - }, - "required": [ - "bad_words" - ] - }, - "url": "https://preview.twilio.com/marketplace/AvailableAddOns/XBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "extensions": "https://preview.twilio.com/marketplace/AvailableAddOns/XBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions" - } - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://preview.twilio.com/marketplace/AvailableAddOns?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://preview.twilio.com/marketplace/AvailableAddOns?PageSize=50&Page=0", - "next_page_url": null, - "key": "available_add_ons" - } - } - ''' - )) - - actual = self.client.preview.marketplace.available_add_ons.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "available_add_ons": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://preview.twilio.com/marketplace/AvailableAddOns?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://preview.twilio.com/marketplace/AvailableAddOns?PageSize=50&Page=0", - "next_page_url": null, - "key": "available_add_ons" - } - } - ''' - )) - - actual = self.client.preview.marketplace.available_add_ons.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/marketplace/test_installed_add_on.py b/tests/integration/preview/marketplace/test_installed_add_on.py deleted file mode 100644 index e3303e1db5..0000000000 --- a/tests/integration/preview/marketplace/test_installed_add_on.py +++ /dev/null @@ -1,231 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class InstalledAddOnTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.marketplace.installed_add_ons.create(available_add_on_sid="XBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", accept_terms_of_service=True) - - values = {'AvailableAddOnSid': "XBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 'AcceptTermsOfService': True, } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/marketplace/InstalledAddOns', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "VoiceBase High Accuracy Transcription", - "description": "Automatic Transcription and Keyword Extract...", - "configuration": { - "bad_words": true - }, - "unique_name": "voicebase_high_accuracy_transcription_1", - "date_created": "2016-04-07T23:52:28Z", - "date_updated": "2016-04-07T23:52:28Z", - "url": "https://preview.twilio.com/marketplace/InstalledAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "extensions": "https://preview.twilio.com/marketplace/InstalledAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions", - "available_add_on": "https://preview.twilio.com/marketplace/AvailableAddOns/XBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - } - ''' - )) - - actual = self.client.preview.marketplace.installed_add_ons.create(available_add_on_sid="XBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", accept_terms_of_service=True) - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.marketplace.installed_add_ons(sid="XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/marketplace/InstalledAddOns/XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.marketplace.installed_add_ons(sid="XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.marketplace.installed_add_ons(sid="XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/marketplace/InstalledAddOns/XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "VoiceBase High Accuracy Transcription", - "description": "Automatic Transcription and Keyword Extract...", - "configuration": { - "bad_words": true - }, - "unique_name": "voicebase_high_accuracy_transcription", - "date_created": "2016-04-07T23:52:28Z", - "date_updated": "2016-04-07T23:52:28Z", - "url": "https://preview.twilio.com/marketplace/InstalledAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "extensions": "https://preview.twilio.com/marketplace/InstalledAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions", - "available_add_on": "https://preview.twilio.com/marketplace/AvailableAddOns/XBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - } - ''' - )) - - actual = self.client.preview.marketplace.installed_add_ons(sid="XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.marketplace.installed_add_ons(sid="XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/marketplace/InstalledAddOns/XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "VoiceBase High Accuracy Transcription", - "description": "Automatic Transcription and Keyword Extract...", - "configuration": { - "bad_words": true - }, - "unique_name": "voicebase_high_accuracy_transcription_2", - "date_created": "2016-04-07T23:52:28Z", - "date_updated": "2016-04-07T23:52:28Z", - "url": "https://preview.twilio.com/marketplace/InstalledAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "extensions": "https://preview.twilio.com/marketplace/InstalledAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions", - "available_add_on": "https://preview.twilio.com/marketplace/AvailableAddOns/XBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - } - ''' - )) - - actual = self.client.preview.marketplace.installed_add_ons(sid="XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.marketplace.installed_add_ons.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/marketplace/InstalledAddOns', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "installed_add_ons": [ - { - "sid": "XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "VoiceBase High Accuracy Transcription", - "description": "Automatic Transcription and Keyword Extract...", - "configuration": { - "bad_words": true - }, - "unique_name": "voicebase_high_accuracy_transcription", - "date_created": "2016-04-07T23:52:28Z", - "date_updated": "2016-04-07T23:52:28Z", - "url": "https://preview.twilio.com/marketplace/InstalledAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "extensions": "https://preview.twilio.com/marketplace/InstalledAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions", - "available_add_on": "https://preview.twilio.com/marketplace/AvailableAddOns/XBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://preview.twilio.com/marketplace/InstalledAddOns?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://preview.twilio.com/marketplace/InstalledAddOns?PageSize=50&Page=0", - "next_page_url": null, - "key": "installed_add_ons" - } - } - ''' - )) - - actual = self.client.preview.marketplace.installed_add_ons.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "installed_add_ons": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://preview.twilio.com/marketplace/InstalledAddOns?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://preview.twilio.com/marketplace/InstalledAddOns?PageSize=50&Page=0", - "next_page_url": null, - "key": "installed_add_ons" - } - } - ''' - )) - - actual = self.client.preview.marketplace.installed_add_ons.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/proxy/__init__.py b/tests/integration/preview/proxy/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/proxy/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/proxy/service/__init__.py b/tests/integration/preview/proxy/service/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/proxy/service/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/proxy/service/session/__init__.py b/tests/integration/preview/proxy/service/session/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/proxy/service/session/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/proxy/service/session/participant/__init__.py b/tests/integration/preview/proxy/service/session/participant/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/proxy/service/session/participant/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/proxy/service/session/participant/test_message_interaction.py b/tests/integration/preview/proxy/service/session/participant/test_message_interaction.py deleted file mode 100644 index fcbee3a5ea..0000000000 --- a/tests/integration/preview/proxy/service/session/participant/test_message_interaction.py +++ /dev/null @@ -1,155 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class MessageInteractionTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .message_interactions.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/MessageInteractions', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "data": "body", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "participant_sid": "KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "inbound_participant_sid": null, - "inbound_resource_sid": null, - "inbound_resource_status": null, - "inbound_resource_type": null, - "inbound_resource_url": null, - "outbound_participant_sid": "KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "outbound_resource_sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "outbound_resource_status": "sent", - "outbound_resource_type": "Message", - "outbound_resource_url": null, - "sid": "KIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "completed", - "url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessageInteractions/KIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "session_sid": "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .message_interactions.create() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .message_interactions(sid="KIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/MessageInteractions/KIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "data": "data", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "participant_sid": "KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "inbound_participant_sid": null, - "inbound_resource_sid": null, - "inbound_resource_status": null, - "inbound_resource_type": null, - "inbound_resource_url": null, - "outbound_participant_sid": "KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "outbound_resource_sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "outbound_resource_status": "sent", - "outbound_resource_type": "Message", - "outbound_resource_url": null, - "sid": "KIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "completed", - "url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessageInteractions/KIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "session_sid": "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .message_interactions(sid="KIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .message_interactions.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/MessageInteractions', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "interactions": [], - "meta": { - "previous_page_url": null, - "next_page_url": null, - "url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessageInteractions?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessageInteractions?PageSize=50&Page=0", - "page_size": 50, - "key": "interactions" - } - } - ''' - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .message_interactions.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/proxy/service/session/test_interaction.py b/tests/integration/preview/proxy/service/session/test_interaction.py deleted file mode 100644 index c653adeab1..0000000000 --- a/tests/integration/preview/proxy/service/session/test_interaction.py +++ /dev/null @@ -1,100 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class InteractionTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .interactions(sid="KIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Interactions/KIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "data": "data", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "inbound_participant_sid": "KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "inbound_resource_sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "inbound_resource_status": "sent", - "inbound_resource_type": "Message", - "inbound_resource_url": null, - "outbound_participant_sid": "KPbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - "outbound_resource_sid": "SMbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - "outbound_resource_status": "sent", - "outbound_resource_type": "Message", - "outbound_resource_url": null, - "sid": "KIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "completed", - "url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Interactions/KIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "session_sid": "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .interactions(sid="KIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .interactions.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Interactions', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "interactions": [], - "meta": { - "previous_page_url": null, - "next_page_url": null, - "url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Interactions?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Interactions?PageSize=50&Page=0", - "page_size": 50, - "key": "interactions" - } - } - ''' - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .interactions.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/proxy/service/session/test_participant.py b/tests/integration/preview/proxy/service/session/test_participant.py deleted file mode 100644 index 7fe210fd13..0000000000 --- a/tests/integration/preview/proxy/service/session/test_participant.py +++ /dev/null @@ -1,207 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ParticipantTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "participant_type": "sms", - "identifier": "identifier", - "date_updated": "2015-07-30T20:00:00Z", - "proxy_identifier": "proxy_identifier", - "friendly_name": "friendly_name", - "date_created": "2015-07-30T20:00:00Z", - "url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "message_interactions": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessageInteractions" - }, - "sid": "KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "session_sid": "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "previous_page_url": null, - "next_page_url": null, - "url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants?PageSize=50&Page=0", - "page_size": 50, - "key": "participants" - }, - "participants": [] - } - ''' - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.create(identifier="identifier") - - values = {'Identifier': "identifier", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "participant_type": "sms", - "identifier": "identifier", - "date_updated": "2015-07-30T20:00:00Z", - "proxy_identifier": "proxy_identifier", - "friendly_name": "friendly_name", - "date_created": "2015-07-30T20:00:00Z", - "url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "message_interactions": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessageInteractions" - }, - "sid": "KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "session_sid": "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.create(identifier="identifier") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "participant_type": "sms", - "identifier": "identifier", - "date_updated": "2015-07-30T20:00:00Z", - "proxy_identifier": "proxy_identifier", - "friendly_name": "friendly_name", - "date_created": "2015-07-30T20:00:00Z", - "url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "message_interactions": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessageInteractions" - }, - "sid": "KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "session_sid": "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/proxy/service/test_phone_number.py b/tests/integration/preview/proxy/service/test_phone_number.py deleted file mode 100644 index 4aa39b8e77..0000000000 --- a/tests/integration/preview/proxy/service/test_phone_number.py +++ /dev/null @@ -1,159 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class PhoneNumberTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers.create(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = {'Sid': "PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/PhoneNumbers', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "phone_number": "+987654321", - "country_code": "US", - "capabilities": [], - "url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers.create(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/PhoneNumbers/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/PhoneNumbers', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers?PageSize=50&Page=0", - "previous_page_url": null, - "next_page_url": null, - "key": "phone_numbers", - "url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers?PageSize=50&Page=0" - }, - "phone_numbers": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "phone_number": "+987654321", - "country_code": "US", - "capabilities": [], - "url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/PhoneNumbers/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "phone_number": "12345", - "country_code": "US", - "capabilities": [], - "url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/proxy/service/test_session.py b/tests/integration/preview/proxy/service/test_session.py deleted file mode 100644 index f33111d567..0000000000 --- a/tests/integration/preview/proxy/service/test_session.py +++ /dev/null @@ -1,197 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class SessionTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "in-progess", - "unique_name": "unique_name", - "start_time": "2015-07-30T20:00:00Z", - "links": { - "interactions": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Interactions", - "participants": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants" - }, - "ttl": 100, - "date_updated": "2015-07-30T20:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "end_time": "2015-07-30T20:00:00Z", - "url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sessions": [], - "meta": { - "previous_page_url": null, - "next_page_url": null, - "url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions?PageSize=50&Page=0", - "page_size": 50, - "key": "sessions" - } - } - ''' - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "in-progess", - "unique_name": "unique_name", - "start_time": "2015-07-30T20:00:00Z", - "links": { - "interactions": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Interactions", - "participants": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants" - }, - "ttl": 100, - "date_updated": "2015-07-30T20:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "end_time": "2015-07-30T20:00:00Z", - "url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions.create() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "in-progess", - "unique_name": "unique_name", - "start_time": "2015-07-30T20:00:00Z", - "links": { - "interactions": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Interactions", - "participants": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants" - }, - "ttl": 100, - "date_updated": "2015-07-30T20:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "end_time": "2015-07-30T20:00:00Z", - "url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/proxy/service/test_short_code.py b/tests/integration/preview/proxy/service/test_short_code.py deleted file mode 100644 index 26f17670f9..0000000000 --- a/tests/integration/preview/proxy/service/test_short_code.py +++ /dev/null @@ -1,159 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ShortCodeTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes.create(sid="SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = {'Sid': "SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ShortCodes', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "short_code": "12345", - "country_code": "US", - "capabilities": [], - "url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes/SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes.create(sid="SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes(sid="SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ShortCodes/SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes(sid="SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ShortCodes', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes?PageSize=50&Page=0", - "previous_page_url": null, - "next_page_url": null, - "key": "short_codes", - "url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes?PageSize=50&Page=0" - }, - "short_codes": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "short_code": "12345", - "country_code": "US", - "capabilities": [], - "url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes/SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes(sid="SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ShortCodes/SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "short_code": "12345", - "country_code": "US", - "capabilities": [], - "url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes/SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes(sid="SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/proxy/test_service.py b/tests/integration/preview/proxy/test_service.py deleted file mode 100644 index 2fe1df0fd4..0000000000 --- a/tests/integration/preview/proxy/test_service.py +++ /dev/null @@ -1,181 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ServiceTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "friendly_name": "friendly_name", - "date_created": "2015-07-30T20:00:00Z", - "url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "sessions": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions", - "phone_numbers": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers", - "short_codes": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes" - }, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "callback_url": "http://www.example.com", - "auto_create": false - } - ''' - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Proxy/Services', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "previous_page_url": null, - "next_page_url": null, - "url": "https://preview.twilio.com/Proxy/Services?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://preview.twilio.com/Proxy/Services?PageSize=50&Page=0", - "page_size": 50, - "key": "services" - }, - "services": [] - } - ''' - )) - - actual = self.client.preview.proxy.services.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Proxy/Services', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "friendly_name": "friendly_name", - "date_created": "2015-07-30T20:00:00Z", - "url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "sessions": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions", - "phone_numbers": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers", - "short_codes": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes" - }, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "callback_url": "http://www.example.com", - "auto_create": false - } - ''' - )) - - actual = self.client.preview.proxy.services.create() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Proxy/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "friendly_name": "friendly_name", - "date_created": "2015-07-30T20:00:00Z", - "url": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "sessions": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions", - "phone_numbers": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers", - "short_codes": "https://preview.twilio.com/Proxy/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes" - }, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "callback_url": "http://www.example.com", - "auto_create": false - } - ''' - )) - - actual = self.client.preview.proxy.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/studio/__init__.py b/tests/integration/preview/studio/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/studio/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/studio/flow/__init__.py b/tests/integration/preview/studio/flow/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/studio/flow/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/studio/flow/engagement/__init__.py b/tests/integration/preview/studio/flow/engagement/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/studio/flow/engagement/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/studio/flow/engagement/test_step.py b/tests/integration/preview/studio/flow/engagement/test_step.py deleted file mode 100644 index 73d3ddc370..0000000000 --- a/tests/integration/preview/studio/flow/engagement/test_step.py +++ /dev/null @@ -1,92 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class StepTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.studio.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements(sid="FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .steps.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Studio/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Engagements/FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Steps', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "previous_page_url": null, - "next_page_url": null, - "url": "https://preview.twilio.com/Studio/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Engagements/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://preview.twilio.com/Studio/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Engagements/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps?PageSize=50&Page=0", - "page_size": 50, - "key": "steps" - }, - "steps": [] - } - ''' - )) - - actual = self.client.preview.studio.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements(sid="FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .steps.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.studio.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements(sid="FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .steps(sid="FTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Studio/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Engagements/FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Steps/FTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "FTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "engagement_sid": "FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "name": "incomingRequest", - "context": {}, - "transitioned_from": "Trigger", - "transitioned_to": "Ended", - "date_created": "2017-11-06T12:00:00Z", - "date_updated": null, - "url": "https://preview.twilio.com/Studio/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Engagements/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps/FTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.studio.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements(sid="FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .steps(sid="FTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/studio/flow/test_engagement.py b/tests/integration/preview/studio/flow/test_engagement.py deleted file mode 100644 index 442fef43d4..0000000000 --- a/tests/integration/preview/studio/flow/test_engagement.py +++ /dev/null @@ -1,136 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class EngagementTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.studio.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Studio/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Engagements', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "previous_page_url": null, - "next_page_url": null, - "url": "https://preview.twilio.com/Studio/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Engagements?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://preview.twilio.com/Studio/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Engagements?PageSize=50&Page=0", - "page_size": 50, - "key": "engagements" - }, - "engagements": [] - } - ''' - )) - - actual = self.client.preview.studio.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.studio.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements(sid="FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Studio/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Engagements/FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "contact_sid": "FCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "contact_channel_address": "+14155555555", - "status": "ended", - "context": {}, - "date_created": "2017-11-06T12:00:00Z", - "date_updated": null, - "url": "https://preview.twilio.com/Studio/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Engagements/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "steps": "https://preview.twilio.com/Studio/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Engagements/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps" - } - } - ''' - )) - - actual = self.client.preview.studio.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements(sid="FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.studio.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements.create(to="+15558675310", from_="+15017122661") - - values = {'To': "+15558675310", 'From': "+15017122661", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Studio/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Engagements', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "url": "https://preview.twilio.com/Studio/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Engagements/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "context": { - "flow": { - "first_name": "Foo" - } - }, - "contact_sid": "FCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "contact_channel_address": "+18001234567", - "status": "active", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "steps": "https://preview.twilio.com/Studio/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Engagements/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps" - } - } - ''' - )) - - actual = self.client.preview.studio.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements.create(to="+15558675310", from_="+15017122661") - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/studio/test_flow.py b/tests/integration/preview/studio/test_flow.py deleted file mode 100644 index 287cba89e9..0000000000 --- a/tests/integration/preview/studio/test_flow.py +++ /dev/null @@ -1,106 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class FlowTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.studio.flows.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Studio/Flows', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "previous_page_url": null, - "next_page_url": null, - "url": "https://preview.twilio.com/Studio/Flows?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://preview.twilio.com/Studio/Flows?PageSize=50&Page=0", - "page_size": 50, - "key": "flows" - }, - "flows": [] - } - ''' - )) - - actual = self.client.preview.studio.flows.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.studio.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Studio/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Test Flow", - "status": "published", - "debug": false, - "version": 1, - "date_created": "2017-11-06T12:00:00Z", - "date_updated": null, - "url": "https://preview.twilio.com/Studio/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "engagements": "https://preview.twilio.com/Studio/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Engagements" - } - } - ''' - )) - - actual = self.client.preview.studio.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.studio.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/Studio/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.studio.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/preview/sync/__init__.py b/tests/integration/preview/sync/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/sync/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/sync/service/__init__.py b/tests/integration/preview/sync/service/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/sync/service/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/sync/service/document/__init__.py b/tests/integration/preview/sync/service/document/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/sync/service/document/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/sync/service/document/test_document_permission.py b/tests/integration/preview/sync/service/document/test_document_permission.py deleted file mode 100644 index dbc3664e53..0000000000 --- a/tests/integration/preview/sync/service/document/test_document_permission.py +++ /dev/null @@ -1,189 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class DocumentPermissionTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions(identity="identity").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions/identity', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "document_sid": "ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "identity", - "read": true, - "write": true, - "manage": true, - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions/identity" - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions(identity="identity").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions(identity="identity").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions/identity', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions(identity="identity").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "permissions": [], - "meta": { - "first_page_url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/sidOrUniqueName/Permissions?PageSize=50&Page=0", - "key": "permissions", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/sidOrUniqueName/Permissions?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "permissions": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "document_sid": "ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "identity", - "read": true, - "write": true, - "manage": true, - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions/identity" - } - ], - "meta": { - "first_page_url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/sidOrUniqueName/Permissions?PageSize=50&Page=0", - "key": "permissions", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/sidOrUniqueName/Permissions?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions(identity="identity").update(read=True, write=True, manage=True) - - values = {'Read': True, 'Write': True, 'Manage': True, } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions/identity', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "document_sid": "ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "identity", - "read": true, - "write": true, - "manage": true, - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions/identity" - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions(identity="identity").update(read=True, write=True, manage=True) - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/sync/service/sync_list/__init__.py b/tests/integration/preview/sync/service/sync_list/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/sync/service/sync_list/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/sync/service/sync_list/test_sync_list_item.py b/tests/integration/preview/sync/service/sync_list/test_sync_list_item.py deleted file mode 100644 index 924b28e2ed..0000000000 --- a/tests/integration/preview/sync/service/sync_list/test_sync_list_item.py +++ /dev/null @@ -1,237 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base import serialize -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class SyncListItemTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items(index=1).fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items/1', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "data": {}, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "index": 100, - "list_sid": "ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items/100" - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items(index=1).fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items(index=1).delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items/1', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items(index=1).delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items.create(data={}) - - values = {'Data': serialize.object({}), } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "data": {}, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "index": 100, - "list_sid": "ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items/100" - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items.create(data={}) - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "items": [], - "meta": { - "first_page_url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items?PageSize=50&Page=0", - "key": "items", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "items": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "data": {}, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "index": 100, - "list_sid": "ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items/100" - } - ], - "meta": { - "first_page_url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items?PageSize=50&Page=0", - "key": "items", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items(index=1).update(data={}) - - values = {'Data': serialize.object({}), } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items/1', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "data": {}, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "index": 100, - "list_sid": "ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items/100" - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items(index=1).update(data={}) - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/sync/service/sync_list/test_sync_list_permission.py b/tests/integration/preview/sync/service/sync_list/test_sync_list_permission.py deleted file mode 100644 index df418e19e0..0000000000 --- a/tests/integration/preview/sync/service/sync_list/test_sync_list_permission.py +++ /dev/null @@ -1,189 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class SyncListPermissionTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions(identity="identity").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions/identity', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "list_sid": "ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "identity", - "read": true, - "write": true, - "manage": true, - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions/identity" - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions(identity="identity").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions(identity="identity").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions/identity', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions(identity="identity").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "permissions": [], - "meta": { - "first_page_url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/sidOrUniqueName/Permissions?PageSize=50&Page=0", - "key": "permissions", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/sidOrUniqueName/Permissions?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "permissions": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "list_sid": "ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "identity", - "read": true, - "write": true, - "manage": true, - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions/identity" - } - ], - "meta": { - "first_page_url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/sidOrUniqueName/Permissions?PageSize=50&Page=0", - "key": "permissions", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/sidOrUniqueName/Permissions?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions(identity="identity").update(read=True, write=True, manage=True) - - values = {'Read': True, 'Write': True, 'Manage': True, } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions/identity', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "list_sid": "ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "identity", - "read": true, - "write": true, - "manage": true, - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions/identity" - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions(identity="identity").update(read=True, write=True, manage=True) - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/sync/service/sync_map/__init__.py b/tests/integration/preview/sync/service/sync_map/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/sync/service/sync_map/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/sync/service/sync_map/test_sync_map_item.py b/tests/integration/preview/sync/service/sync_map/test_sync_map_item.py deleted file mode 100644 index 14946a709c..0000000000 --- a/tests/integration/preview/sync/service/sync_map/test_sync_map_item.py +++ /dev/null @@ -1,237 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base import serialize -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class SyncMapItemTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items(key="key").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items/key', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "data": {}, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "key": "key", - "map_sid": "MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items/key" - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items(key="key").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items(key="key").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items/key', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items(key="key").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items.create(key="key", data={}) - - values = {'Key': "key", 'Data': serialize.object({}), } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "data": {}, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "key": "key", - "map_sid": "MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items/key" - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items.create(key="key", data={}) - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "items": [], - "meta": { - "first_page_url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items?PageSize=50&Page=0", - "key": "items", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "items": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "data": {}, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "key": "key", - "map_sid": "MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items/key" - } - ], - "meta": { - "first_page_url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items?PageSize=50&Page=0", - "key": "items", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items(key="key").update(data={}) - - values = {'Data': serialize.object({}), } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items/key', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "data": {}, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "key": "key", - "map_sid": "MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items/key" - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items(key="key").update(data={}) - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/sync/service/sync_map/test_sync_map_permission.py b/tests/integration/preview/sync/service/sync_map/test_sync_map_permission.py deleted file mode 100644 index 612fad11de..0000000000 --- a/tests/integration/preview/sync/service/sync_map/test_sync_map_permission.py +++ /dev/null @@ -1,189 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class SyncMapPermissionTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions(identity="identity").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions/identity', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "map_sid": "MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "identity", - "read": true, - "write": true, - "manage": true, - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions/identity" - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions(identity="identity").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions(identity="identity").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions/identity', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions(identity="identity").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "permissions": [], - "meta": { - "first_page_url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/sidOrUniqueName/Permissions?PageSize=50&Page=0", - "key": "permissions", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/sidOrUniqueName/Permissions?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "permissions": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "map_sid": "MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "identity", - "read": true, - "write": true, - "manage": true, - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions/identity" - } - ], - "meta": { - "first_page_url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/sidOrUniqueName/Permissions?PageSize=50&Page=0", - "key": "permissions", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/sidOrUniqueName/Permissions?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions(identity="identity").update(read=True, write=True, manage=True) - - values = {'Read': True, 'Write': True, 'Manage': True, } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions/identity', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "map_sid": "MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "identity", - "read": true, - "write": true, - "manage": true, - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions/identity" - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions(identity="identity").update(read=True, write=True, manage=True) - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/sync/service/test_document.py b/tests/integration/preview/sync/service/test_document.py deleted file mode 100644 index 1eb9e112b2..0000000000 --- a/tests/integration/preview/sync/service/test_document.py +++ /dev/null @@ -1,235 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base import serialize -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class DocumentTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "data": {}, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "permissions": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions" - } - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "data": {}, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "permissions": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions" - } - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents.create() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "documents": [], - "meta": { - "first_page_url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents?PageSize=50&Page=0", - "key": "documents", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "documents": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "data": {}, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "permissions": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions" - } - } - ], - "meta": { - "first_page_url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents?PageSize=50&Page=0", - "key": "documents", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(data={}) - - values = {'Data': serialize.object({}), } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "data": {}, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "permissions": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions" - } - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(data={}) - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/sync/service/test_sync_list.py b/tests/integration/preview/sync/service/test_sync_list.py deleted file mode 100644 index 4799f830e4..0000000000 --- a/tests/integration/preview/sync/service/test_sync_list.py +++ /dev/null @@ -1,192 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class SyncListTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "items": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items", - "permissions": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions" - }, - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "items": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items", - "permissions": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions" - }, - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists.create() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "lists": [], - "meta": { - "first_page_url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists?PageSize=50&Page=0", - "key": "lists", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "lists": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "items": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items", - "permissions": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions" - }, - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists?PageSize=50&Page=0", - "key": "lists", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/sync/service/test_sync_map.py b/tests/integration/preview/sync/service/test_sync_map.py deleted file mode 100644 index fae07700b6..0000000000 --- a/tests/integration/preview/sync/service/test_sync_map.py +++ /dev/null @@ -1,192 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class SyncMapTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "items": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items", - "permissions": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions" - }, - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "items": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items", - "permissions": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions" - }, - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps.create() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "maps": [], - "meta": { - "first_page_url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps?PageSize=50&Page=0", - "key": "maps", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "maps": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "items": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items", - "permissions": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions" - }, - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps?PageSize=50&Page=0", - "key": "maps", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/sync/test_service.py b/tests/integration/preview/sync/test_service.py deleted file mode 100644 index 0c0ba005d6..0000000000 --- a/tests/integration/preview/sync/test_service.py +++ /dev/null @@ -1,224 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ServiceTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "links": { - "documents": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents", - "lists": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists", - "maps": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps" - }, - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "webhook_url": "http://www.example.com", - "reachability_webhooks_enabled": false, - "acl_enabled": false - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Sync/Services', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "links": { - "documents": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents", - "lists": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists", - "maps": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps" - }, - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "webhook_url": "http://www.example.com", - "reachability_webhooks_enabled": false, - "acl_enabled": true - } - ''' - )) - - actual = self.client.preview.sync.services.create() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/Sync/Services', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://preview.twilio.com/Sync/Services?PageSize=50&Page=0", - "key": "services", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/Sync/Services?PageSize=50&Page=0" - }, - "services": [] - } - ''' - )) - - actual = self.client.preview.sync.services.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://preview.twilio.com/Sync/Services?PageSize=50&Page=0", - "key": "services", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/Sync/Services?PageSize=50&Page=0" - }, - "services": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "links": { - "documents": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents", - "lists": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists", - "maps": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps" - }, - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "webhook_url": "http://www.example.com", - "reachability_webhooks_enabled": false, - "acl_enabled": false - } - ] - } - ''' - )) - - actual = self.client.preview.sync.services.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "links": { - "documents": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents", - "lists": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists", - "maps": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps" - }, - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "webhook_url": "http://www.example.com", - "reachability_webhooks_enabled": false, - "acl_enabled": true - } - ''' - )) - - actual = self.client.preview.sync.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/understand/__init__.py b/tests/integration/preview/understand/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/understand/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/understand/assistant/__init__.py b/tests/integration/preview/understand/assistant/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/understand/assistant/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/understand/assistant/field_type/__init__.py b/tests/integration/preview/understand/assistant/field_type/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/understand/assistant/field_type/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/understand/assistant/field_type/test_field_value.py b/tests/integration/preview/understand/assistant/field_type/test_field_value.py deleted file mode 100644 index 3be7b68983..0000000000 --- a/tests/integration/preview/understand/assistant/field_type/test_field_value.py +++ /dev/null @@ -1,195 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class FieldValueTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types(sid="UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_values(sid="UCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/FieldTypes/UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/FieldValues/UCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldValues/UCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "field_type_sid": "UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "language": "language", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "value": "value", - "date_updated": "2015-07-30T20:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "sid": "UCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "synonym_of": null - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types(sid="UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_values(sid="UCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types(sid="UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_values.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/FieldTypes/UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/FieldValues', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "field_values": [], - "meta": { - "first_page_url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldValues?PageSize=50&Page=0", - "page_size": 50, - "previous_page_url": null, - "key": "field_values", - "page": 0, - "next_page_url": null, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldValues?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types(sid="UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_values.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "field_values": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldValues/UCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "field_type_sid": "UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "language": "language", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "value": "value", - "date_updated": "2015-07-30T20:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "sid": "UCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "synonym_of": "UCbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" - } - ], - "meta": { - "first_page_url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldValues?PageSize=50&Page=0", - "page_size": 50, - "previous_page_url": null, - "key": "field_values", - "page": 0, - "next_page_url": null, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldValues?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types(sid="UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_values.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types(sid="UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_values.create(language="language", value="value") - - values = {'Language': "language", 'Value': "value", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/FieldTypes/UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/FieldValues', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldValues/UCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "field_type_sid": "UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "language": "language", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "value": "value", - "date_updated": "2015-07-30T20:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "sid": "UCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "synonym_of": "UCbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types(sid="UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_values.create(language="language", value="value") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types(sid="UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_values(sid="UCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/FieldTypes/UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/FieldValues/UCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types(sid="UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_values(sid="UCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/preview/understand/assistant/intent/__init__.py b/tests/integration/preview/understand/assistant/intent/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/understand/assistant/intent/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/understand/assistant/intent/test_field.py b/tests/integration/preview/understand/assistant/intent/test_field.py deleted file mode 100644 index c3ac0365db..0000000000 --- a/tests/integration/preview/understand/assistant/intent/test_field.py +++ /dev/null @@ -1,192 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class FieldTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .fields(sid="UEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Intents/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Fields/UEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields/UEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "date_updated": "2015-07-30T20:00:00Z", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "intent_sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "sid": "UEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "field_type": "field_type" - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .fields(sid="UEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .fields.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Intents/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Fields', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "fields": [], - "meta": { - "page": 0, - "first_page_url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields?PageSize=50&Page=0", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields?PageSize=50&Page=0", - "key": "fields", - "next_page_url": null, - "previous_page_url": null, - "page_size": 50 - } - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .fields.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "fields": [ - { - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields/UEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "date_updated": "2015-07-30T20:00:00Z", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "intent_sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "sid": "UEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "field_type": "field_type" - } - ], - "meta": { - "page": 0, - "first_page_url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields?PageSize=50&Page=0", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields?PageSize=50&Page=0", - "key": "fields", - "next_page_url": null, - "previous_page_url": null, - "page_size": 50 - } - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .fields.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .fields.create(field_type="field_type", unique_name="unique_name") - - values = {'FieldType': "field_type", 'UniqueName': "unique_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Intents/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Fields', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields/UEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "date_updated": "2015-07-30T20:00:00Z", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "intent_sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "sid": "UEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "field_type": "field_type" - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .fields.create(field_type="field_type", unique_name="unique_name") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .fields(sid="UEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Intents/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Fields/UEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .fields(sid="UEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/preview/understand/assistant/intent/test_sample.py b/tests/integration/preview/understand/assistant/intent/test_sample.py deleted file mode 100644 index 4888f5bee1..0000000000 --- a/tests/integration/preview/understand/assistant/intent/test_sample.py +++ /dev/null @@ -1,233 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class SampleTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples(sid="UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Intents/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Samples/UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples/UFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "intent_sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "language": "language", - "tagged_text": "tagged_text", - "date_updated": "2015-07-30T20:00:00Z", - "source_channel": null - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples(sid="UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Intents/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Samples', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "samples": [], - "meta": { - "first_page_url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples?PageSize=50&Page=0", - "previous_page_url": null, - "key": "samples", - "next_page_url": null, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples?PageSize=50&Page=0", - "page": 0, - "page_size": 50 - } - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "samples": [ - { - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples/UFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "intent_sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "language": "language", - "tagged_text": "tagged_text", - "date_updated": "2015-07-30T20:00:00Z", - "source_channel": "sms" - } - ], - "meta": { - "first_page_url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples?PageSize=50&Page=0", - "previous_page_url": null, - "key": "samples", - "next_page_url": null, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples?PageSize=50&Page=0", - "page": 0, - "page_size": 50 - } - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples.create(language="language", tagged_text="tagged_text") - - values = {'Language': "language", 'TaggedText': "tagged_text", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Intents/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Samples', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples/UFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "intent_sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "language": "language", - "tagged_text": "tagged_text", - "date_updated": "2015-07-30T20:00:00Z", - "source_channel": "alexa" - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples.create(language="language", tagged_text="tagged_text") - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples(sid="UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Intents/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Samples/UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples/UFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "intent_sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "language": "language", - "tagged_text": "tagged_text", - "date_updated": "2015-07-30T20:00:00Z", - "source_channel": "alexa" - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples(sid="UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples(sid="UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Intents/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Samples/UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples(sid="UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/preview/understand/assistant/test_field_type.py b/tests/integration/preview/understand/assistant/test_field_type.py deleted file mode 100644 index 4e326b7786..0000000000 --- a/tests/integration/preview/understand/assistant/test_field_type.py +++ /dev/null @@ -1,226 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class FieldTypeTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types(sid="UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/FieldTypes/UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "unique_name": "unique_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "field_values": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldValues" - }, - "sid": "UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types(sid="UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/FieldTypes', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes?PageSize=50&Page=0", - "first_page_url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes?PageSize=50&Page=0", - "previous_page_url": null, - "page": 0, - "page_size": 50, - "next_page_url": null, - "key": "field_types" - }, - "field_types": [] - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes?PageSize=50&Page=0", - "first_page_url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes?PageSize=50&Page=0", - "previous_page_url": null, - "page": 0, - "page_size": 50, - "next_page_url": null, - "key": "field_types" - }, - "field_types": [ - { - "unique_name": "unique_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "field_values": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldValues" - }, - "sid": "UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types.create(unique_name="unique_name") - - values = {'UniqueName': "unique_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/FieldTypes', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "unique_name": "unique_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "field_values": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldValues" - }, - "sid": "UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types.create(unique_name="unique_name") - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types(sid="UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/FieldTypes/UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "unique_name": "unique_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "field_values": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldValues" - }, - "sid": "UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types(sid="UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types(sid="UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/FieldTypes/UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types(sid="UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/preview/understand/assistant/test_intent.py b/tests/integration/preview/understand/assistant/test_intent.py deleted file mode 100644 index f15ead7cf5..0000000000 --- a/tests/integration/preview/understand/assistant/test_intent.py +++ /dev/null @@ -1,230 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class IntentTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Intents/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "unique_name": "unique_name", - "links": { - "fields": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields", - "samples": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples" - }, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z" - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Intents', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "key": "intents", - "page_size": 50, - "next_page_url": null, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents?PageSize=50&Page=0", - "previous_page_url": null - }, - "intents": [] - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "key": "intents", - "page_size": 50, - "next_page_url": null, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents?PageSize=50&Page=0", - "previous_page_url": null - }, - "intents": [ - { - "unique_name": "unique_name", - "links": { - "fields": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields", - "samples": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples" - }, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z" - } - ] - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents.create(unique_name="unique_name") - - values = {'UniqueName': "unique_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Intents', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "unique_name": "unique_name", - "links": { - "fields": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields", - "samples": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples" - }, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z" - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents.create(unique_name="unique_name") - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Intents/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "unique_name": "unique_name", - "links": { - "fields": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields", - "samples": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples" - }, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z" - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Intents/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .intents(sid="UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/preview/understand/assistant/test_model_build.py b/tests/integration/preview/understand/assistant/test_model_build.py deleted file mode 100644 index 5db58e31ea..0000000000 --- a/tests/integration/preview/understand/assistant/test_model_build.py +++ /dev/null @@ -1,219 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ModelBuildTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds(sid="UGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ModelBuilds/UGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ModelBuilds/UGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "enqueued", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "sid": "UGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "build_duration": null, - "error_code": null - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds(sid="UGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ModelBuilds', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "key": "model_builds", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ModelBuilds?PageSize=50&Page=0", - "first_page_url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ModelBuilds?PageSize=50&Page=0", - "next_page_url": null, - "previous_page_url": null, - "page_size": 50 - }, - "model_builds": [] - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "key": "model_builds", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ModelBuilds?PageSize=50&Page=0", - "first_page_url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ModelBuilds?PageSize=50&Page=0", - "next_page_url": null, - "previous_page_url": null, - "page_size": 50 - }, - "model_builds": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ModelBuilds/UGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "failed", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "sid": "UGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "build_duration": null, - "error_code": 23001 - } - ] - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ModelBuilds', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ModelBuilds/UGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "enqueued", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "sid": "UGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "build_duration": null, - "error_code": null - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds.create() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds(sid="UGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ModelBuilds/UGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ModelBuilds/UGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "completed", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "sid": "UGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "build_duration": 100, - "error_code": null - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds(sid="UGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds(sid="UGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ModelBuilds/UGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds(sid="UGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/preview/understand/assistant/test_query.py b/tests/integration/preview/understand/assistant/test_query.py deleted file mode 100644 index 5d75c007bd..0000000000 --- a/tests/integration/preview/understand/assistant/test_query.py +++ /dev/null @@ -1,286 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class QueryTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries(sid="UHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Queries/UHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "language": "language", - "date_created": "2015-07-30T20:00:00Z", - "model_build_sid": "UGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "query": "query", - "date_updated": "2015-07-30T20:00:00Z", - "status": "status", - "sample_sid": "UFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "results": { - "intent": { - "name": "name", - "intent_sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "confidence": 0.9 - }, - "entities": [ - { - "name": "name", - "value": "value", - "type": "type" - } - ] - }, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries/UHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "source_channel": "voice" - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries(sid="UHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Queries', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "queries": [], - "meta": { - "previous_page_url": null, - "next_page_url": null, - "first_page_url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries?PageSize=50&Page=0", - "page": 0, - "key": "queries", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries?PageSize=50&Page=0", - "page_size": 50 - } - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "queries": [ - { - "language": "language", - "date_created": "2015-07-30T20:00:00Z", - "model_build_sid": "UGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "query": "query", - "date_updated": "2015-07-30T20:00:00Z", - "status": "status", - "sample_sid": "UFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "results": { - "intent": { - "name": "name", - "intent_sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "confidence": 0.9 - }, - "entities": [ - { - "name": "name", - "value": "value", - "type": "type" - } - ] - }, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries/UHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "source_channel": null - } - ], - "meta": { - "previous_page_url": null, - "next_page_url": null, - "first_page_url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries?PageSize=50&Page=0", - "page": 0, - "key": "queries", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries?PageSize=50&Page=0", - "page_size": 50 - } - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries.create(language="language", query="query") - - values = {'Language': "language", 'Query': "query", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Queries', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "language": "language", - "date_created": "2015-07-30T20:00:00Z", - "model_build_sid": "UGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "query": "query", - "date_updated": "2015-07-30T20:00:00Z", - "status": "status", - "sample_sid": "UFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "results": { - "intent": { - "name": "name", - "intent_sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "confidence": 0.9 - }, - "entities": [ - { - "name": "name", - "value": "value", - "type": "type" - } - ] - }, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries/UHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "source_channel": "voice" - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries.create(language="language", query="query") - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries(sid="UHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Queries/UHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "language": "language", - "date_created": "2015-07-30T20:00:00Z", - "model_build_sid": "UGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "query": "query", - "date_updated": "2015-07-30T20:00:00Z", - "status": "status", - "sample_sid": "UFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "results": { - "intent": { - "name": "name", - "intent_sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "confidence": 0.9 - }, - "entities": [ - { - "name": "name", - "value": "value", - "type": "type" - } - ] - }, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries/UHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "source_channel": "sms" - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries(sid="UHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries(sid="UHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Queries/UHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries(sid="UHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/preview/understand/test_assistant.py b/tests/integration/preview/understand/test_assistant.py deleted file mode 100644 index 068d25039b..0000000000 --- a/tests/integration/preview/understand/test_assistant.py +++ /dev/null @@ -1,244 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class AssistantTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2017-07-04T08:34:00Z", - "date_updated": "2017-07-04T08:34:00Z", - "friendly_name": "so so friendly", - "latest_model_build_sid": null, - "log_queries": true, - "sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ttl": 3600, - "unique_name": "so-so-unique", - "links": { - "field_types": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes", - "intents": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents", - "model_builds": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ModelBuilds", - "queries": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries" - }, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "response_url": "https://example.com/response_url", - "callback_url": "https://example.com/callback_url", - "callback_events": "model_build_completed model_build_failed" - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "assistants": [], - "meta": { - "first_page_url": "https://preview.twilio.com/understand/Assistants?PageSize=50&Page=0", - "key": "assistants", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/understand/Assistants?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.understand.assistants.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "assistants": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2017-07-04T08:34:00Z", - "date_updated": "2017-07-04T08:34:00Z", - "friendly_name": "so so friendly", - "latest_model_build_sid": null, - "log_queries": true, - "sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ttl": 3600, - "unique_name": "so-so-unique", - "links": { - "field_types": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes", - "intents": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents", - "model_builds": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ModelBuilds", - "queries": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries" - }, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "response_url": "https://example.com/response_url", - "callback_url": "https://example.com/callback_url", - "callback_events": "model_build_completed model_build_failed" - } - ], - "meta": { - "first_page_url": "https://preview.twilio.com/understand/Assistants?PageSize=50&Page=0", - "key": "assistants", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/understand/Assistants?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.understand.assistants.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/understand/Assistants', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2017-07-04T08:34:00Z", - "date_updated": "2017-07-04T08:34:00Z", - "friendly_name": "so so friendly", - "latest_model_build_sid": null, - "log_queries": true, - "sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ttl": 3600, - "unique_name": "so-so-unique", - "links": { - "field_types": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes", - "intents": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents", - "model_builds": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ModelBuilds", - "queries": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries" - }, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "response_url": "https://example.com/response_url", - "callback_url": "https://example.com/callback_url", - "callback_events": "model_build_completed model_build_failed" - } - ''' - )) - - actual = self.client.preview.understand.assistants.create() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2017-07-04T08:34:00Z", - "date_updated": "2017-07-04T08:34:00Z", - "friendly_name": "so so friendly", - "latest_model_build_sid": null, - "log_queries": true, - "sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ttl": 3600, - "unique_name": "so-so-unique", - "links": { - "field_types": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes", - "intents": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Intents", - "model_builds": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ModelBuilds", - "queries": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries" - }, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "response_url": "https://example.com/response_url", - "callback_url": "https://example.com/callback_url", - "callback_events": "model_build_completed model_build_failed" - } - ''' - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.understand.assistants(sid="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/preview/wireless/__init__.py b/tests/integration/preview/wireless/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/wireless/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/wireless/sim/__init__.py b/tests/integration/preview/wireless/sim/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/preview/wireless/sim/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/wireless/sim/test_usage.py b/tests/integration/preview/wireless/sim/test_usage.py deleted file mode 100644 index e35da0630f..0000000000 --- a/tests/integration/preview/wireless/sim/test_usage.py +++ /dev/null @@ -1,50 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class UsageTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.wireless.sims(sid="DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/wireless/Sims/DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Usage', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "commands_costs": {}, - "commands_usage": {}, - "data_costs": {}, - "data_usage": {}, - "sim_unique_name": "sim_unique_name", - "sim_sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "period": {}, - "url": "https://preview.twilio.com/wireless/Sims/DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage" - } - ''' - )) - - actual = self.client.preview.wireless.sims(sid="DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/wireless/test_command.py b/tests/integration/preview/wireless/test_command.py deleted file mode 100644 index 7ec1ed9066..0000000000 --- a/tests/integration/preview/wireless/test_command.py +++ /dev/null @@ -1,159 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class CommandTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.wireless.commands(sid="DCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/wireless/Commands/DCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "command": "command", - "command_mode": "command_mode", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "device_sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sim_sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "direction": "direction", - "sid": "DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "status", - "url": "https://preview.twilio.com/wireless/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.wireless.commands(sid="DCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.wireless.commands.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/wireless/Commands', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "commands": [], - "meta": { - "first_page_url": "https://preview.twilio.com/wireless/Commands?PageSize=50&Page=0", - "key": "commands", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/wireless/Commands?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.wireless.commands.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "commands": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "command": "command", - "command_mode": "command_mode", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "device_sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sim_sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "direction": "direction", - "sid": "DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "status", - "url": "https://preview.twilio.com/wireless/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://preview.twilio.com/wireless/Commands?PageSize=50&Page=0", - "key": "commands", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/wireless/Commands?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.wireless.commands.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.wireless.commands.create(command="command") - - values = {'Command': "command", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/wireless/Commands', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "command": "command", - "command_mode": "command_mode", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "device_sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sim_sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "direction": "direction", - "sid": "DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "status", - "url": "https://preview.twilio.com/wireless/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.wireless.commands.create(command="command") - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/wireless/test_rate_plan.py b/tests/integration/preview/wireless/test_rate_plan.py deleted file mode 100644 index 28d6b406f6..0000000000 --- a/tests/integration/preview/wireless/test_rate_plan.py +++ /dev/null @@ -1,240 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class RatePlanTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.wireless.rate_plans.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/wireless/RatePlans', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://preview.twilio.com/wireless/RatePlans?PageSize=50&Page=0", - "key": "rate_plans", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/wireless/RatePlans?PageSize=50&Page=0" - }, - "rate_plans": [] - } - ''' - )) - - actual = self.client.preview.wireless.rate_plans.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://preview.twilio.com/wireless/RatePlans?PageSize=50&Page=0", - "key": "rate_plans", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/wireless/RatePlans?PageSize=50&Page=0" - }, - "rate_plans": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "data_enabled": true, - "data_limit": 1000, - "data_metering": "pooled", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "messaging_enabled": true, - "voice_enabled": true, - "national_roaming_enabled": true, - "international_roaming": [ - "data", - "messaging", - "voice" - ], - "sid": "WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://preview.twilio.com/wireless/RatePlans/WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.preview.wireless.rate_plans.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.wireless.rate_plans(sid="WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/wireless/RatePlans/WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "data_enabled": true, - "data_limit": 1000, - "data_metering": "pooled", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "messaging_enabled": true, - "voice_enabled": true, - "national_roaming_enabled": true, - "international_roaming": [ - "data", - "messaging", - "voice" - ], - "sid": "WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://preview.twilio.com/wireless/RatePlans/WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.wireless.rate_plans(sid="WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.wireless.rate_plans.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/wireless/RatePlans', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "data_enabled": true, - "data_limit": 1000, - "data_metering": "pooled", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "messaging_enabled": true, - "voice_enabled": true, - "national_roaming_enabled": true, - "international_roaming": [ - "data", - "messaging", - "voice" - ], - "sid": "WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://preview.twilio.com/wireless/RatePlans/WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.wireless.rate_plans.create() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.wireless.rate_plans(sid="WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/wireless/RatePlans/WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "data_enabled": true, - "data_limit": 1000, - "data_metering": "pooled", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "messaging_enabled": true, - "voice_enabled": true, - "national_roaming_enabled": true, - "international_roaming": [ - "data", - "messaging", - "voice" - ], - "sid": "WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://preview.twilio.com/wireless/RatePlans/WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.wireless.rate_plans(sid="WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.wireless.rate_plans(sid="WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/wireless/RatePlans/WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.wireless.rate_plans(sid="WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/preview/wireless/test_sim.py b/tests/integration/preview/wireless/test_sim.py deleted file mode 100644 index b2dd6b0fb1..0000000000 --- a/tests/integration/preview/wireless/test_sim.py +++ /dev/null @@ -1,198 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class SimTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.wireless.sims(sid="DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/wireless/Sims/DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "commands_callback_method": "http_method", - "commands_callback_url": "http://www.example.com", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "sms_fallback_method": "http_method", - "sms_fallback_url": "http://www.example.com", - "sms_method": "http_method", - "sms_url": "http://www.example.com", - "voice_fallback_method": "http_method", - "voice_fallback_url": "http://www.example.com", - "voice_method": "http_method", - "voice_url": "http://www.example.com", - "links": { - "usage": "https://preview.twilio.com/wireless/Sims/DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage", - "rate_plan": "https://preview.twilio.com/wireless/RatePlans/WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "rate_plan_sid": "WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "iccid": "iccid", - "e_id": "e_id", - "status": "status", - "url": "https://preview.twilio.com/wireless/Sims/DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.wireless.sims(sid="DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.wireless.sims.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/wireless/Sims', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sims": [], - "meta": { - "first_page_url": "https://preview.twilio.com/wireless/Sims?PageSize=50&Page=0", - "key": "sims", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/wireless/Sims?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.wireless.sims.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sims": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "commands_callback_method": "http_method", - "commands_callback_url": "http://www.example.com", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "links": { - "usage": "https://preview.twilio.com/wireless/Sims/DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage", - "rate_plan": "https://preview.twilio.com/wireless/RatePlans/WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "rate_plan_sid": "WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "iccid": "iccid", - "e_id": "e_id", - "status": "status", - "sms_fallback_method": "http_method", - "sms_fallback_url": "http://www.example.com", - "sms_method": "http_method", - "sms_url": "http://www.example.com", - "voice_fallback_method": "http_method", - "voice_fallback_url": "http://www.example.com", - "voice_method": "http_method", - "voice_url": "http://www.example.com", - "url": "https://preview.twilio.com/wireless/Sims/DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://preview.twilio.com/wireless/Sims?PageSize=50&Page=0", - "key": "sims", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://preview.twilio.com/wireless/Sims?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.wireless.sims.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.wireless.sims(sid="DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/wireless/Sims/DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "commands_callback_method": "http_method", - "commands_callback_url": "http://www.example.com", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "links": { - "usage": "https://preview.twilio.com/wireless/Sims/DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage", - "rate_plan": "https://preview.twilio.com/wireless/RatePlans/WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "rate_plan_sid": "WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "iccid": "iccid", - "e_id": "e_id", - "status": "status", - "sms_fallback_method": "http_method", - "sms_fallback_url": "http://www.example.com", - "sms_method": "http_method", - "sms_url": "http://www.example.com", - "voice_fallback_method": "http_method", - "voice_fallback_url": "http://www.example.com", - "voice_method": "http_method", - "voice_url": "http://www.example.com", - "url": "https://preview.twilio.com/wireless/Sims/DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.wireless.sims(sid="DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/pricing/__init__.py b/tests/integration/pricing/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/pricing/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/pricing/v1/__init__.py b/tests/integration/pricing/v1/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/pricing/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/pricing/v1/messaging/__init__.py b/tests/integration/pricing/v1/messaging/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/pricing/v1/messaging/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/pricing/v1/messaging/test_country.py b/tests/integration/pricing/v1/messaging/test_country.py deleted file mode 100644 index f7aae4a8e4..0000000000 --- a/tests/integration/pricing/v1/messaging/test_country.py +++ /dev/null @@ -1,132 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class CountryTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.pricing.v1.messaging \ - .countries.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://pricing.twilio.com/v1/Messaging/Countries', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "countries": [], - "meta": { - "first_page_url": "https://pricing.twilio.com/v1/Messaging/Countries?Page=0&PageSize=50", - "key": "countries", - "next_page_url": null, - "page": 0, - "page_size": 0, - "previous_page_url": null, - "url": "https://pricing.twilio.com/v1/Messaging/Countries" - } - } - ''' - )) - - actual = self.client.pricing.v1.messaging \ - .countries.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "countries": [ - { - "country": "country", - "iso_country": "US", - "url": "http://www.example.com" - } - ], - "meta": { - "first_page_url": "https://pricing.twilio.com/v1/Messaging/Countries?Page=0&PageSize=50", - "key": "countries", - "next_page_url": null, - "page": 0, - "page_size": 1, - "previous_page_url": null, - "url": "https://pricing.twilio.com/v1/Messaging/Countries" - } - } - ''' - )) - - actual = self.client.pricing.v1.messaging \ - .countries.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.pricing.v1.messaging \ - .countries(iso_country="US").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://pricing.twilio.com/v1/Messaging/Countries/US', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "country": "country", - "inbound_sms_prices": [ - { - "base_price": 0.05, - "current_price": 0.05, - "number_type": "mobile" - } - ], - "iso_country": "US", - "outbound_sms_prices": [ - { - "carrier": "att", - "mcc": "foo", - "mnc": "bar", - "prices": [ - { - "base_price": 0.05, - "current_price": 0.05, - "number_type": "mobile" - } - ] - } - ], - "price_unit": "USD", - "url": "http://www.example.com" - } - ''' - )) - - actual = self.client.pricing.v1.messaging \ - .countries(iso_country="US").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/pricing/v1/phone_number/__init__.py b/tests/integration/pricing/v1/phone_number/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/pricing/v1/phone_number/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/pricing/v1/phone_number/test_country.py b/tests/integration/pricing/v1/phone_number/test_country.py deleted file mode 100644 index 30de6631fa..0000000000 --- a/tests/integration/pricing/v1/phone_number/test_country.py +++ /dev/null @@ -1,123 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class CountryTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.pricing.v1.phone_numbers \ - .countries.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://pricing.twilio.com/v1/PhoneNumbers/Countries', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "countries": [ - { - "country": "Austria", - "iso_country": "AT", - "url": "https://pricing.twilio.com/v1/PhoneNumbers/Countries/AT" - } - ], - "meta": { - "first_page_url": "https://pricing.twilio.com/v1/PhoneNumbers/Countries?PageSize=1&Page=0", - "key": "countries", - "next_page_url": null, - "page": 0, - "page_size": 1, - "previous_page_url": null, - "url": "https://pricing.twilio.com/v1/PhoneNumbers/Countries?PageSize=1&Page=0" - } - } - ''' - )) - - actual = self.client.pricing.v1.phone_numbers \ - .countries.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "countries": [], - "meta": { - "first_page_url": "https://pricing.twilio.com/v1/PhoneNumbers/Countries?PageSize=1&Page=0", - "key": "countries", - "next_page_url": null, - "page": 0, - "page_size": 1, - "previous_page_url": null, - "url": "https://pricing.twilio.com/v1/PhoneNumbers/Countries?PageSize=1&Page=0" - } - } - ''' - )) - - actual = self.client.pricing.v1.phone_numbers \ - .countries.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.pricing.v1.phone_numbers \ - .countries(iso_country="US").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://pricing.twilio.com/v1/PhoneNumbers/Countries/US', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "country": "Estonia", - "iso_country": "EE", - "phone_number_prices": [ - { - "base_price": 3.0, - "current_price": 3.0, - "type": "mobile" - }, - { - "base_price": 1.0, - "current_price": 1.0, - "type": "national" - } - ], - "price_unit": "usd", - "url": "https://pricing.twilio.com/v1/PhoneNumbers/Countries/US" - } - ''' - )) - - actual = self.client.pricing.v1.phone_numbers \ - .countries(iso_country="US").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/pricing/v1/test_messaging.py b/tests/integration/pricing/v1/test_messaging.py deleted file mode 100644 index 5673b56b23..0000000000 --- a/tests/integration/pricing/v1/test_messaging.py +++ /dev/null @@ -1,16 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class MessagingTestCase(IntegrationTestCase): - pass diff --git a/tests/integration/pricing/v1/test_phone_number.py b/tests/integration/pricing/v1/test_phone_number.py deleted file mode 100644 index 9170c53e58..0000000000 --- a/tests/integration/pricing/v1/test_phone_number.py +++ /dev/null @@ -1,16 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class PhoneNumberTestCase(IntegrationTestCase): - pass diff --git a/tests/integration/pricing/v1/test_voice.py b/tests/integration/pricing/v1/test_voice.py deleted file mode 100644 index 01830ea2fe..0000000000 --- a/tests/integration/pricing/v1/test_voice.py +++ /dev/null @@ -1,16 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class VoiceTestCase(IntegrationTestCase): - pass diff --git a/tests/integration/pricing/v1/voice/__init__.py b/tests/integration/pricing/v1/voice/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/pricing/v1/voice/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/pricing/v1/voice/test_country.py b/tests/integration/pricing/v1/voice/test_country.py deleted file mode 100644 index 85ff23d6ed..0000000000 --- a/tests/integration/pricing/v1/voice/test_country.py +++ /dev/null @@ -1,261 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class CountryTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.pricing.v1.voice \ - .countries.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://pricing.twilio.com/v1/Voice/Countries', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "countries": [ - { - "country": "Andorra", - "iso_country": "AD", - "url": "https://pricing.twilio.com/v1/Voice/Countries/AD" - } - ], - "meta": { - "first_page_url": "https://pricing.twilio.com/v1/Voice/Countries?PageSize=1&Page=0", - "key": "countries", - "next_page_url": null, - "page": 0, - "page_size": 1, - "previous_page_url": null, - "url": "https://pricing.twilio.com/v1/Voice/Countries?PageSize=1&Page=0" - } - } - ''' - )) - - actual = self.client.pricing.v1.voice \ - .countries.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "countries": [], - "meta": { - "first_page_url": "https://pricing.twilio.com/v1/Voice/Countries?PageSize=1&Page=0", - "key": "countries", - "next_page_url": null, - "page": 0, - "page_size": 1, - "previous_page_url": null, - "url": "https://pricing.twilio.com/v1/Voice/Countries?PageSize=1&Page=0" - } - } - ''' - )) - - actual = self.client.pricing.v1.voice \ - .countries.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.pricing.v1.voice \ - .countries(iso_country="US").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://pricing.twilio.com/v1/Voice/Countries/US', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "country": "Australia", - "inbound_call_prices": [ - { - "base_price": "0.0075", - "current_price": "0.0075", - "number_type": "local" - } - ], - "iso_country": "AU", - "outbound_prefix_prices": [ - { - "base_price": "0.024", - "current_price": "0.024", - "friendly_name": "Programmable Outbound Minute - Australia - Major Cities", - "prefixes": [ - "6128", - "6129", - "6138", - "6139", - "6173", - "61261", - "61262", - "61861", - "61862", - "61863", - "61864", - "61865", - "61870", - "61881", - "61882", - "61883", - "61884", - "61892", - "61893", - "61894" - ] - }, - { - "base_price": "0.035", - "current_price": "0.035", - "friendly_name": "Programmable Outbound Minute - Australia", - "prefixes": [ - "61" - ] - }, - { - "base_price": "0.095", - "current_price": "0.095", - "friendly_name": "Programmable Outbound Minute - Australia - Shared Cost Service", - "prefixes": [ - "6113" - ] - }, - { - "base_price": "0.095", - "current_price": "0.095", - "friendly_name": "Programmable Outbound Minute - Australia - Mobile", - "prefixes": [ - "614", - "6116", - "61400", - "61401", - "61402", - "61403", - "61404", - "61405", - "61406", - "61407", - "61408", - "61409", - "61410", - "61411", - "61412", - "61413", - "61414", - "61415", - "61416", - "61417", - "61418", - "61419", - "61421", - "61422", - "61423", - "61424", - "61425", - "61426", - "61427", - "61428", - "61429", - "61430", - "61431", - "61432", - "61433", - "61434", - "61435", - "61437", - "61438", - "61439", - "61447", - "61448", - "61449", - "61450", - "61451", - "61452", - "61453", - "61455", - "61456", - "61457", - "61458", - "61459", - "61466", - "61467", - "61474", - "61477", - "61478", - "61481", - "61482", - "61487", - "61490", - "61497", - "61498", - "61499", - "614202", - "614203", - "614204", - "614205", - "614206", - "614207", - "614208", - "614209", - "614444", - "614683", - "614684", - "614685", - "614686", - "614687", - "614688", - "614689", - "614790", - "614791", - "614880", - "614881", - "614882", - "614883", - "614884", - "614885", - "614886", - "614887", - "614889" - ] - } - ], - "price_unit": "USD", - "url": "https://pricing.twilio.com/v1/Voice/Countries/US" - } - ''' - )) - - actual = self.client.pricing.v1.voice \ - .countries(iso_country="US").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/pricing/v1/voice/test_number.py b/tests/integration/pricing/v1/voice/test_number.py deleted file mode 100644 index 45e08e8103..0000000000 --- a/tests/integration/pricing/v1/voice/test_number.py +++ /dev/null @@ -1,55 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class NumberTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.pricing.v1.voice \ - .numbers(number="+15017122661").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://pricing.twilio.com/v1/Voice/Numbers/+15017122661', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "country": "United States", - "inbound_call_price": { - "base_price": null, - "current_price": null, - "number_type": null - }, - "iso_country": "US", - "number": "+987654321", - "outbound_call_price": { - "base_price": "0.015", - "current_price": "0.015" - }, - "price_unit": "USD", - "url": "https://pricing.twilio.com/v1/Voice/Numbers/+987654321" - } - ''' - )) - - actual = self.client.pricing.v1.voice \ - .numbers(number="+15017122661").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/proxy/__init__.py b/tests/integration/proxy/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/proxy/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/proxy/v1/__init__.py b/tests/integration/proxy/v1/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/proxy/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/proxy/v1/service/__init__.py b/tests/integration/proxy/v1/service/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/proxy/v1/service/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/proxy/v1/service/session/__init__.py b/tests/integration/proxy/v1/service/session/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/proxy/v1/service/session/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/proxy/v1/service/session/participant/__init__.py b/tests/integration/proxy/v1/service/session/participant/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/proxy/v1/service/session/participant/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/proxy/v1/service/session/participant/test_message_interaction.py b/tests/integration/proxy/v1/service/session/participant/test_message_interaction.py deleted file mode 100644 index 80e4d0887f..0000000000 --- a/tests/integration/proxy/v1/service/session/participant/test_message_interaction.py +++ /dev/null @@ -1,155 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class MessageInteractionTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .message_interactions.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/MessageInteractions', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "data": "body", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "participant_sid": "KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "inbound_participant_sid": null, - "inbound_resource_sid": null, - "inbound_resource_status": null, - "inbound_resource_type": null, - "inbound_resource_url": null, - "outbound_participant_sid": "KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "outbound_resource_sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "outbound_resource_status": "sent", - "outbound_resource_type": "Message", - "outbound_resource_url": null, - "sid": "KIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "type": "message", - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessageInteractions/KIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "session_sid": "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .message_interactions.create() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .message_interactions(sid="KIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/MessageInteractions/KIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "data": "data", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "participant_sid": "KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "inbound_participant_sid": null, - "inbound_resource_sid": null, - "inbound_resource_status": null, - "inbound_resource_type": null, - "inbound_resource_url": null, - "outbound_participant_sid": "KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "outbound_resource_sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "outbound_resource_status": "sent", - "outbound_resource_type": "Message", - "outbound_resource_url": null, - "sid": "KIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "type": "message", - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessageInteractions/KIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "session_sid": "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .message_interactions(sid="KIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .message_interactions.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/MessageInteractions', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "interactions": [], - "meta": { - "previous_page_url": null, - "next_page_url": null, - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessageInteractions?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessageInteractions?PageSize=50&Page=0", - "page_size": 50, - "key": "interactions" - } - } - ''' - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .message_interactions.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/proxy/v1/service/session/test_interaction.py b/tests/integration/proxy/v1/service/session/test_interaction.py deleted file mode 100644 index a3914ac597..0000000000 --- a/tests/integration/proxy/v1/service/session/test_interaction.py +++ /dev/null @@ -1,125 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class InteractionTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .interactions(sid="KIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Interactions/KIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "data": "data", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "inbound_participant_sid": "KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "inbound_resource_sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "inbound_resource_status": "sent", - "inbound_resource_type": "Message", - "inbound_resource_url": null, - "outbound_participant_sid": "KPbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - "outbound_resource_sid": "SMbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - "outbound_resource_status": "sent", - "outbound_resource_type": "Message", - "outbound_resource_url": null, - "sid": "KIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "type": "message", - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Interactions/KIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "session_sid": "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .interactions(sid="KIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .interactions.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Interactions', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "interactions": [], - "meta": { - "previous_page_url": null, - "next_page_url": null, - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Interactions?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Interactions?PageSize=50&Page=0", - "page_size": 50, - "key": "interactions" - } - } - ''' - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .interactions.list() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .interactions(sid="KIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Interactions/KIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .interactions(sid="KIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/proxy/v1/service/session/test_participant.py b/tests/integration/proxy/v1/service/session/test_participant.py deleted file mode 100644 index 32bc64b27c..0000000000 --- a/tests/integration/proxy/v1/service/session/test_participant.py +++ /dev/null @@ -1,210 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ParticipantTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "session_sid": "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identifier": "identifier", - "proxy_identifier": "proxy_identifier", - "proxy_identifier_sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "date_deleted": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "message_interactions": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessageInteractions" - } - } - ''' - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "previous_page_url": null, - "next_page_url": null, - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants?PageSize=50&Page=0", - "page_size": 50, - "key": "participants" - }, - "participants": [] - } - ''' - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.create(identifier="identifier") - - values = {'Identifier': "identifier", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "session_sid": "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identifier": "identifier", - "proxy_identifier": "proxy_identifier", - "proxy_identifier_sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "date_deleted": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "message_interactions": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessageInteractions" - } - } - ''' - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.create(identifier="identifier") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "session_sid": "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identifier": "identifier", - "proxy_identifier": "proxy_identifier", - "proxy_identifier_sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "date_deleted": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "message_interactions": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessageInteractions" - } - } - ''' - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/proxy/v1/service/test_phone_number.py b/tests/integration/proxy/v1/service/test_phone_number.py deleted file mode 100644 index 05f3fb747f..0000000000 --- a/tests/integration/proxy/v1/service/test_phone_number.py +++ /dev/null @@ -1,168 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class PhoneNumberTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/PhoneNumbers', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "phone_number": "+987654321", - "friendly_name": "Friendly Name", - "iso_country": "US", - "capabilities": { - "sms_outbound": true, - "voice_inbound": false - }, - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers.create() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/PhoneNumbers/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/PhoneNumbers', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers?PageSize=50&Page=0", - "previous_page_url": null, - "next_page_url": null, - "key": "phone_numbers", - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers?PageSize=50&Page=0" - }, - "phone_numbers": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "phone_number": "+987654321", - "friendly_name": "Friendly Name", - "iso_country": "US", - "capabilities": { - "sms_outbound": true, - "voice_inbound": false - }, - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/PhoneNumbers/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "phone_number": "12345", - "friendly_name": "Friendly Name", - "iso_country": "US", - "capabilities": { - "sms_outbound": true, - "voice_inbound": false - }, - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/proxy/v1/service/test_session.py b/tests/integration/proxy/v1/service/test_session.py deleted file mode 100644 index f6d40a0b40..0000000000 --- a/tests/integration/proxy/v1/service/test_session.py +++ /dev/null @@ -1,209 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class SessionTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "in-progress", - "unique_name": "unique_name", - "date_started": "2015-07-30T20:00:00Z", - "date_ended": "2015-07-30T20:00:00Z", - "date_last_interaction": "2015-07-30T20:00:00Z", - "date_expiry": "2015-07-30T20:00:00Z", - "ttl": 3600, - "mode": "message-only", - "closed_reason": "", - "sid": "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "interactions": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Interactions", - "participants": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants" - } - } - ''' - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sessions": [], - "meta": { - "previous_page_url": null, - "next_page_url": null, - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions?PageSize=50&Page=0", - "page_size": 50, - "key": "sessions" - } - } - ''' - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "in-progress", - "unique_name": "unique_name", - "date_started": "2015-07-30T20:00:00Z", - "date_ended": "2015-07-30T20:00:00Z", - "date_last_interaction": "2015-07-30T20:00:00Z", - "date_expiry": "2015-07-30T20:00:00Z", - "ttl": 3600, - "mode": "message-only", - "closed_reason": "", - "sid": "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "interactions": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Interactions", - "participants": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants" - } - } - ''' - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions.create() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sessions/KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "in-progress", - "unique_name": "unique_name", - "date_started": "2015-07-30T20:00:00Z", - "date_ended": "2015-07-30T20:00:00Z", - "date_last_interaction": "2015-07-30T20:00:00Z", - "date_expiry": "2015-07-30T20:00:00Z", - "ttl": 3600, - "mode": "message-only", - "closed_reason": "", - "sid": "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "interactions": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Interactions", - "participants": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions/KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants" - } - } - ''' - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions(sid="KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/proxy/v1/service/test_short_code.py b/tests/integration/proxy/v1/service/test_short_code.py deleted file mode 100644 index 1b4a7329dc..0000000000 --- a/tests/integration/proxy/v1/service/test_short_code.py +++ /dev/null @@ -1,168 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ShortCodeTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes.create(sid="SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = {'Sid': "SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ShortCodes', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "short_code": "12345", - "iso_country": "US", - "capabilities": { - "sms_outbound": true, - "voice_inbound": false - }, - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes/SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes.create(sid="SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes(sid="SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ShortCodes/SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes(sid="SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ShortCodes', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes?PageSize=50&Page=0", - "previous_page_url": null, - "next_page_url": null, - "key": "short_codes", - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes?PageSize=50&Page=0" - }, - "short_codes": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "short_code": "12345", - "iso_country": "US", - "capabilities": { - "sms_outbound": true, - "voice_inbound": false - }, - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes/SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes(sid="SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ShortCodes/SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "short_code": "12345", - "iso_country": "US", - "capabilities": { - "sms_outbound": true, - "voice_inbound": false - }, - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes/SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes(sid="SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/proxy/v1/test_service.py b/tests/integration/proxy/v1/test_service.py deleted file mode 100644 index 7dafcbc1c4..0000000000 --- a/tests/integration/proxy/v1/test_service.py +++ /dev/null @@ -1,196 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ServiceTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "default_ttl": 3600, - "callback_url": "http://www.example.com", - "geo_match_level": "country", - "number_selection_behavior": "prefer_sticky", - "intercept_callback_url": "http://www.example.com", - "out_of_session_callback_url": "http://www.example.com", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "sessions": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions", - "phone_numbers": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers", - "short_codes": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes" - } - } - ''' - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://proxy.twilio.com/v1/Services', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "services": [], - "meta": { - "first_page_url": "https://proxy.twilio.com/v1/Services?PageSize=50&Page=0", - "key": "services", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://proxy.twilio.com/v1/Services?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.proxy.v1.services.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services.create(unique_name="unique_name") - - values = {'UniqueName': "unique_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://proxy.twilio.com/v1/Services', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "default_ttl": 3600, - "callback_url": "http://www.example.com", - "geo_match_level": "country", - "number_selection_behavior": "prefer_sticky", - "intercept_callback_url": "http://www.example.com", - "out_of_session_callback_url": "http://www.example.com", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "sessions": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions", - "phone_numbers": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers", - "short_codes": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes" - } - } - ''' - )) - - actual = self.client.proxy.v1.services.create(unique_name="unique_name") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "default_ttl": 3600, - "callback_url": "http://www.example.com", - "geo_match_level": "country", - "number_selection_behavior": "prefer_sticky", - "intercept_callback_url": "http://www.example.com", - "out_of_session_callback_url": "http://www.example.com", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "sessions": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Sessions", - "phone_numbers": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers", - "short_codes": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes" - } - } - ''' - )) - - actual = self.client.proxy.v1.services(sid="KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/studio/__init__.py b/tests/integration/studio/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/studio/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/studio/v1/__init__.py b/tests/integration/studio/v1/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/studio/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/studio/v1/flow/__init__.py b/tests/integration/studio/v1/flow/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/studio/v1/flow/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/studio/v1/flow/engagement/__init__.py b/tests/integration/studio/v1/flow/engagement/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/studio/v1/flow/engagement/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/studio/v1/flow/engagement/step/__init__.py b/tests/integration/studio/v1/flow/engagement/step/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/studio/v1/flow/engagement/step/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/studio/v1/flow/engagement/step/test_step_context.py b/tests/integration/studio/v1/flow/engagement/step/test_step_context.py deleted file mode 100644 index cd161c5ae2..0000000000 --- a/tests/integration/studio/v1/flow/engagement/step/test_step_context.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class StepContextTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v1.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements(sid="FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .steps(sid="FTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .step_context().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://studio.twilio.com/v1/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Engagements/FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Steps/FTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Context', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "context": { - "foo": "bar" - }, - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "engagement_sid": "FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "step_sid": "FTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Engagements/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps/FTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Context" - } - ''' - )) - - actual = self.client.studio.v1.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements(sid="FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .steps(sid="FTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .step_context().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/studio/v1/flow/engagement/test_engagement_context.py b/tests/integration/studio/v1/flow/engagement/test_engagement_context.py deleted file mode 100644 index f9adfb49f0..0000000000 --- a/tests/integration/studio/v1/flow/engagement/test_engagement_context.py +++ /dev/null @@ -1,50 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class EngagementContextTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v1.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements(sid="FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagement_context().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://studio.twilio.com/v1/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Engagements/FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Context', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "context": { - "foo": "bar" - }, - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "engagement_sid": "FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Engagements/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Context" - } - ''' - )) - - actual = self.client.studio.v1.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements(sid="FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagement_context().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/studio/v1/flow/engagement/test_step.py b/tests/integration/studio/v1/flow/engagement/test_step.py deleted file mode 100644 index 554d60fc06..0000000000 --- a/tests/integration/studio/v1/flow/engagement/test_step.py +++ /dev/null @@ -1,95 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class StepTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v1.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements(sid="FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .steps.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://studio.twilio.com/v1/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Engagements/FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Steps', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "previous_page_url": null, - "next_page_url": null, - "url": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Engagements/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Engagements/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps?PageSize=50&Page=0", - "page_size": 50, - "key": "steps" - }, - "steps": [] - } - ''' - )) - - actual = self.client.studio.v1.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements(sid="FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .steps.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v1.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements(sid="FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .steps(sid="FTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://studio.twilio.com/v1/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Engagements/FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Steps/FTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "FTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "engagement_sid": "FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "name": "incomingRequest", - "context": {}, - "transitioned_from": "Trigger", - "transitioned_to": "Ended", - "date_created": "2017-11-06T12:00:00Z", - "date_updated": null, - "url": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Engagements/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps/FTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "step_context": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Engagements/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps/FTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Context" - } - } - ''' - )) - - actual = self.client.studio.v1.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements(sid="FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .steps(sid="FTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/studio/v1/flow/test_engagement.py b/tests/integration/studio/v1/flow/test_engagement.py deleted file mode 100644 index 89a807a697..0000000000 --- a/tests/integration/studio/v1/flow/test_engagement.py +++ /dev/null @@ -1,134 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class EngagementTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v1.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://studio.twilio.com/v1/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Engagements', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "previous_page_url": null, - "next_page_url": null, - "url": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Engagements?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Engagements?PageSize=50&Page=0", - "page_size": 50, - "key": "engagements" - }, - "engagements": [] - } - ''' - )) - - actual = self.client.studio.v1.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v1.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements(sid="FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://studio.twilio.com/v1/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Engagements/FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "contact_sid": "FCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "contact_channel_address": "+14155555555", - "status": "ended", - "context": {}, - "date_created": "2017-11-06T12:00:00Z", - "date_updated": null, - "url": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Engagements/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "steps": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Engagements/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps", - "engagement_context": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Engagements/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Context" - } - } - ''' - )) - - actual = self.client.studio.v1.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements(sid="FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v1.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements.create(to="+15558675310", from_="+15017122661") - - values = {'To': "+15558675310", 'From': "+15017122661", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://studio.twilio.com/v1/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Engagements', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "url": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Engagements/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "context": {}, - "contact_sid": "FCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "contact_channel_address": "+18001234567", - "status": "active", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "steps": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Engagements/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps", - "engagement_context": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Engagements/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Context" - } - } - ''' - )) - - actual = self.client.studio.v1.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements.create(to="+15558675310", from_="+15017122661") - - self.assertIsNotNone(actual) diff --git a/tests/integration/studio/v1/test_flow.py b/tests/integration/studio/v1/test_flow.py deleted file mode 100644 index d1e26648eb..0000000000 --- a/tests/integration/studio/v1/test_flow.py +++ /dev/null @@ -1,105 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class FlowTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v1.flows.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://studio.twilio.com/v1/Flows', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "previous_page_url": null, - "next_page_url": null, - "url": "https://studio.twilio.com/v1/Flows?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://studio.twilio.com/v1/Flows?PageSize=50&Page=0", - "page_size": 50, - "key": "flows" - }, - "flows": [] - } - ''' - )) - - actual = self.client.studio.v1.flows.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v1.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://studio.twilio.com/v1/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Test Flow", - "status": "published", - "version": 1, - "date_created": "2017-11-06T12:00:00Z", - "date_updated": null, - "url": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "engagements": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Engagements" - } - } - ''' - )) - - actual = self.client.studio.v1.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v1.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://studio.twilio.com/v1/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.studio.v1.flows(sid="FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/sync/__init__.py b/tests/integration/sync/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/sync/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/sync/v1/__init__.py b/tests/integration/sync/v1/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/sync/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/sync/v1/service/__init__.py b/tests/integration/sync/v1/service/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/sync/v1/service/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/sync/v1/service/document/__init__.py b/tests/integration/sync/v1/service/document/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/sync/v1/service/document/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/sync/v1/service/document/test_document_permission.py b/tests/integration/sync/v1/service/document/test_document_permission.py deleted file mode 100644 index 7a15010be6..0000000000 --- a/tests/integration/sync/v1/service/document/test_document_permission.py +++ /dev/null @@ -1,189 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class DocumentPermissionTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions(identity="identity").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions/identity', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "document_sid": "ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "identity", - "read": true, - "write": true, - "manage": true, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions/identity" - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions(identity="identity").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions(identity="identity").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions/identity', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions(identity="identity").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "permissions": [], - "meta": { - "first_page_url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/sidOrUniqueName/Permissions?PageSize=50&Page=0", - "key": "permissions", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/sidOrUniqueName/Permissions?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "permissions": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "document_sid": "ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "identity", - "read": true, - "write": true, - "manage": true, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions/identity" - } - ], - "meta": { - "first_page_url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/sidOrUniqueName/Permissions?PageSize=50&Page=0", - "key": "permissions", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/sidOrUniqueName/Permissions?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions(identity="identity").update(read=True, write=True, manage=True) - - values = {'Read': True, 'Write': True, 'Manage': True, } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions/identity', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "document_sid": "ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "identity", - "read": true, - "write": true, - "manage": true, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions/identity" - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions(identity="identity").update(read=True, write=True, manage=True) - - self.assertIsNotNone(actual) diff --git a/tests/integration/sync/v1/service/sync_list/__init__.py b/tests/integration/sync/v1/service/sync_list/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/sync/v1/service/sync_list/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/sync/v1/service/sync_list/test_sync_list_item.py b/tests/integration/sync/v1/service/sync_list/test_sync_list_item.py deleted file mode 100644 index cf1268327f..0000000000 --- a/tests/integration/sync/v1/service/sync_list/test_sync_list_item.py +++ /dev/null @@ -1,238 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base import serialize -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class SyncListItemTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items(index=1).fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items/1', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "data": {}, - "date_expires": "2015-07-30T21:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "index": 100, - "list_sid": "ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items/100" - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items(index=1).fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items(index=1).delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items/1', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items(index=1).delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items.create(data={}) - - values = {'Data': serialize.object({}), } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "data": {}, - "date_expires": "2015-07-30T21:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "index": 100, - "list_sid": "ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items/100" - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items.create(data={}) - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "items": [], - "meta": { - "first_page_url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items?PageSize=50&Page=0", - "key": "items", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "items": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "data": {}, - "date_expires": "2015-07-30T21:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "index": 100, - "list_sid": "ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items/100" - } - ], - "meta": { - "first_page_url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items?PageSize=50&Page=0", - "key": "items", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items(index=1).update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items/1', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "data": {}, - "date_expires": "2015-07-30T21:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "index": 100, - "list_sid": "ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items/100" - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items(index=1).update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/sync/v1/service/sync_list/test_sync_list_permission.py b/tests/integration/sync/v1/service/sync_list/test_sync_list_permission.py deleted file mode 100644 index 6dece66122..0000000000 --- a/tests/integration/sync/v1/service/sync_list/test_sync_list_permission.py +++ /dev/null @@ -1,189 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class SyncListPermissionTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions(identity="identity").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions/identity', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "list_sid": "ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "identity", - "read": true, - "write": true, - "manage": true, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions/identity" - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions(identity="identity").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions(identity="identity").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions/identity', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions(identity="identity").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "permissions": [], - "meta": { - "first_page_url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/sidOrUniqueName/Permissions?PageSize=50&Page=0", - "key": "permissions", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/sidOrUniqueName/Permissions?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "permissions": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "list_sid": "ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "identity", - "read": true, - "write": true, - "manage": true, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions/identity" - } - ], - "meta": { - "first_page_url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/sidOrUniqueName/Permissions?PageSize=50&Page=0", - "key": "permissions", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/sidOrUniqueName/Permissions?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions(identity="identity").update(read=True, write=True, manage=True) - - values = {'Read': True, 'Write': True, 'Manage': True, } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions/identity', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "list_sid": "ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "identity", - "read": true, - "write": true, - "manage": true, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions/identity" - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions(identity="identity").update(read=True, write=True, manage=True) - - self.assertIsNotNone(actual) diff --git a/tests/integration/sync/v1/service/sync_map/__init__.py b/tests/integration/sync/v1/service/sync_map/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/sync/v1/service/sync_map/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/sync/v1/service/sync_map/test_sync_map_item.py b/tests/integration/sync/v1/service/sync_map/test_sync_map_item.py deleted file mode 100644 index f0b9b32ffc..0000000000 --- a/tests/integration/sync/v1/service/sync_map/test_sync_map_item.py +++ /dev/null @@ -1,238 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base import serialize -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class SyncMapItemTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items(key="key").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items/key', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "data": {}, - "date_expires": "2015-07-30T21:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "key": "key", - "map_sid": "MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items/key" - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items(key="key").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items(key="key").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items/key', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items(key="key").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items.create(key="key", data={}) - - values = {'Key': "key", 'Data': serialize.object({}), } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "data": {}, - "date_expires": "2015-07-30T21:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "key": "key", - "map_sid": "MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items/key" - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items.create(key="key", data={}) - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "items": [], - "meta": { - "first_page_url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items?PageSize=50&Page=0", - "key": "items", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "items": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "data": {}, - "date_expires": "2015-07-30T21:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "key": "key", - "map_sid": "MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items/key" - } - ], - "meta": { - "first_page_url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items?PageSize=50&Page=0", - "key": "items", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items(key="key").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items/key', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "data": {}, - "date_expires": "2015-07-30T21:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "key": "key", - "map_sid": "MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items/key" - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items(key="key").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/sync/v1/service/sync_map/test_sync_map_permission.py b/tests/integration/sync/v1/service/sync_map/test_sync_map_permission.py deleted file mode 100644 index 525366c3d9..0000000000 --- a/tests/integration/sync/v1/service/sync_map/test_sync_map_permission.py +++ /dev/null @@ -1,189 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class SyncMapPermissionTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions(identity="identity").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions/identity', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "map_sid": "MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "identity", - "read": true, - "write": true, - "manage": true, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions/identity" - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions(identity="identity").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions(identity="identity").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions/identity', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions(identity="identity").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "permissions": [], - "meta": { - "first_page_url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/sidOrUniqueName/Permissions?PageSize=50&Page=0", - "key": "permissions", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/sidOrUniqueName/Permissions?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "permissions": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "map_sid": "MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "identity", - "read": true, - "write": true, - "manage": true, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions/identity" - } - ], - "meta": { - "first_page_url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/sidOrUniqueName/Permissions?PageSize=50&Page=0", - "key": "permissions", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/sidOrUniqueName/Permissions?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions(identity="identity").update(read=True, write=True, manage=True) - - values = {'Read': True, 'Write': True, 'Manage': True, } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions/identity', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "map_sid": "MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "identity", - "read": true, - "write": true, - "manage": true, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions/identity" - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions(identity="identity").update(read=True, write=True, manage=True) - - self.assertIsNotNone(actual) diff --git a/tests/integration/sync/v1/service/sync_stream/__init__.py b/tests/integration/sync/v1/service/sync_stream/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/sync/v1/service/sync_stream/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/sync/v1/service/sync_stream/test_stream_message.py b/tests/integration/sync/v1/service/sync_stream/test_stream_message.py deleted file mode 100644 index 6d8e5bcad2..0000000000 --- a/tests/integration/sync/v1/service/sync_stream/test_stream_message.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base import serialize -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class StreamMessageTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_streams(sid="TOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .stream_messages.create(data={}) - - values = {'Data': serialize.object({}), } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Streams/TOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "TZaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "data": {} - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_streams(sid="TOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .stream_messages.create(data={}) - - self.assertIsNotNone(actual) diff --git a/tests/integration/sync/v1/service/test_document.py b/tests/integration/sync/v1/service/test_document.py deleted file mode 100644 index 25a7e0d3d1..0000000000 --- a/tests/integration/sync/v1/service/test_document.py +++ /dev/null @@ -1,235 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class DocumentTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "data": {}, - "date_expires": "2015-07-30T21:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "permissions": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions" - } - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "data": {}, - "date_expires": "2015-07-30T21:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "permissions": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions" - } - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents.create() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "documents": [], - "meta": { - "first_page_url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents?PageSize=50&Page=0", - "key": "documents", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "documents": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "data": {}, - "date_expires": "2015-07-30T21:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "permissions": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions" - } - } - ], - "meta": { - "first_page_url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents?PageSize=50&Page=0", - "key": "documents", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "data": {}, - "date_expires": "2015-07-30T21:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "permissions": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents/ETaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions" - } - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents(sid="ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/sync/v1/service/test_sync_list.py b/tests/integration/sync/v1/service/test_sync_list.py deleted file mode 100644 index d43d2ffef3..0000000000 --- a/tests/integration/sync/v1/service/test_sync_list.py +++ /dev/null @@ -1,235 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class SyncListTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_expires": "2015-07-30T21:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "items": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items", - "permissions": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions" - }, - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_expires": "2015-07-30T21:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "items": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items", - "permissions": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions" - }, - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists.create() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_expires": "2015-07-30T21:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "items": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items", - "permissions": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions" - }, - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists(sid="ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "lists": [], - "meta": { - "first_page_url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists?PageSize=50&Page=0", - "key": "lists", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "lists": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_expires": "2015-07-30T21:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "items": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items", - "permissions": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions" - }, - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists?PageSize=50&Page=0", - "key": "lists", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/sync/v1/service/test_sync_map.py b/tests/integration/sync/v1/service/test_sync_map.py deleted file mode 100644 index b92f840adc..0000000000 --- a/tests/integration/sync/v1/service/test_sync_map.py +++ /dev/null @@ -1,235 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class SyncMapTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_expires": "2015-07-30T21:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "items": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items", - "permissions": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions" - }, - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_expires": "2015-07-30T21:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "items": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items", - "permissions": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions" - }, - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps.create() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_expires": "2015-07-30T21:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "items": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items", - "permissions": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions" - }, - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps(sid="MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "maps": [], - "meta": { - "first_page_url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps?PageSize=50&Page=0", - "key": "maps", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "maps": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_expires": "2015-07-30T21:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "items": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items", - "permissions": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions" - }, - "revision": "revision", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps?PageSize=50&Page=0", - "key": "maps", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/sync/v1/service/test_sync_stream.py b/tests/integration/sync/v1/service/test_sync_stream.py deleted file mode 100644 index b98b580aee..0000000000 --- a/tests/integration/sync/v1/service/test_sync_stream.py +++ /dev/null @@ -1,227 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class SyncStreamTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_streams(sid="TOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Streams/TOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_expires": "2015-07-30T21:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "messages": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Streams/TOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages" - }, - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "TOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Streams/TOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_streams(sid="TOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_streams(sid="TOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Streams/TOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_streams(sid="TOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_streams.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Streams', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_expires": "2015-07-30T21:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "messages": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Streams/TOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages" - }, - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "TOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Streams/TOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_streams.create() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_streams(sid="TOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Streams/TOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_expires": "2015-07-30T21:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "messages": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Streams/TOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages" - }, - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "TOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Streams/TOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_streams(sid="TOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_streams.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Streams', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "streams": [], - "meta": { - "first_page_url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Streams?PageSize=50&Page=0", - "key": "streams", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Streams?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_streams.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "streams": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "created_by": "created_by", - "date_expires": "2015-07-30T21:00:00Z", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "messages": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Streams/TOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages" - }, - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "TOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Streams/TOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Streams?PageSize=50&Page=0", - "key": "streams", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Streams?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_streams.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/sync/v1/test_service.py b/tests/integration/sync/v1/test_service.py deleted file mode 100644 index ed58682772..0000000000 --- a/tests/integration/sync/v1/test_service.py +++ /dev/null @@ -1,232 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ServiceTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "links": { - "documents": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents", - "lists": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists", - "maps": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps", - "streams": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Streams" - }, - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "webhook_url": "http://www.example.com", - "reachability_webhooks_enabled": false, - "acl_enabled": false - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://sync.twilio.com/v1/Services', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "links": { - "documents": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents", - "lists": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists", - "maps": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps", - "streams": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Streams" - }, - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "webhook_url": "http://www.example.com", - "reachability_webhooks_enabled": false, - "acl_enabled": true - } - ''' - )) - - actual = self.client.sync.v1.services.create() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://sync.twilio.com/v1/Services', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://sync.twilio.com/v1/Services?PageSize=50&Page=0", - "key": "services", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://sync.twilio.com/v1/Services?PageSize=50&Page=0" - }, - "services": [] - } - ''' - )) - - actual = self.client.sync.v1.services.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://sync.twilio.com/v1/Services?PageSize=50&Page=0", - "key": "services", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://sync.twilio.com/v1/Services?PageSize=50&Page=0" - }, - "services": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "links": { - "documents": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents", - "lists": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists", - "maps": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps", - "streams": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Streams" - }, - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "webhook_url": "http://www.example.com", - "reachability_webhooks_enabled": false, - "acl_enabled": false - } - ] - } - ''' - )) - - actual = self.client.sync.v1.services.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "links": { - "documents": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Documents", - "lists": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists", - "maps": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps", - "streams": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Streams" - }, - "sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "url": "https://sync.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "webhook_url": "http://www.example.com", - "reachability_webhooks_enabled": false, - "acl_enabled": true - } - ''' - )) - - actual = self.client.sync.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/taskrouter/__init__.py b/tests/integration/taskrouter/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/taskrouter/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/taskrouter/v1/__init__.py b/tests/integration/taskrouter/v1/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/taskrouter/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/taskrouter/v1/test_workspace.py b/tests/integration/taskrouter/v1/test_workspace.py deleted file mode 100644 index a5a766d1cf..0000000000 --- a/tests/integration/taskrouter/v1/test_workspace.py +++ /dev/null @@ -1,275 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class WorkspaceTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-08-01T22:10:40Z", - "date_updated": "2016-08-01T22:10:40Z", - "default_activity_name": "Offline", - "default_activity_sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "event_callback_url": "", - "events_filter": null, - "friendly_name": "new", - "links": { - "activities": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities", - "statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics", - "real_time_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RealTimeStatistics", - "cumulative_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CumulativeStatistics", - "task_queues": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues", - "tasks": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks", - "workers": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers", - "workflows": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows", - "task_channels": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskChannels", - "events": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events" - }, - "multi_task_enabled": false, - "prioritize_queue_order": "FIFO", - "sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "timeout_activity_name": "Offline", - "timeout_activity_sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-08-01T22:10:40Z", - "date_updated": "2016-08-01T22:10:40Z", - "default_activity_name": "Offline", - "default_activity_sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "event_callback_url": "", - "events_filter": null, - "friendly_name": "new", - "links": { - "activities": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities", - "statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics", - "real_time_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RealTimeStatistics", - "cumulative_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CumulativeStatistics", - "task_queues": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues", - "tasks": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks", - "workers": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers", - "workflows": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows", - "task_channels": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskChannels", - "events": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events" - }, - "multi_task_enabled": false, - "prioritize_queue_order": "FIFO", - "sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "timeout_activity_name": "Offline", - "timeout_activity_sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces?PageSize=50&Page=0", - "key": "workspaces", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces?PageSize=50&Page=0" - }, - "workspaces": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-08-01T22:10:40Z", - "date_updated": "2016-08-01T22:10:40Z", - "default_activity_name": "Offline", - "default_activity_sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "event_callback_url": "", - "events_filter": null, - "friendly_name": "new", - "links": { - "activities": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities", - "statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics", - "real_time_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RealTimeStatistics", - "cumulative_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CumulativeStatistics", - "task_queues": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues", - "tasks": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks", - "workers": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers", - "workflows": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows", - "task_channels": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskChannels", - "events": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events" - }, - "multi_task_enabled": false, - "prioritize_queue_order": "FIFO", - "sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "timeout_activity_name": "Offline", - "timeout_activity_sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces?PageSize=50&Page=0", - "key": "workspaces", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces?PageSize=50&Page=0" - }, - "workspaces": [] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces.create(friendly_name="friendly_name") - - values = {'FriendlyName': "friendly_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://taskrouter.twilio.com/v1/Workspaces', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-08-01T22:10:40Z", - "date_updated": "2016-08-01T22:10:40Z", - "default_activity_name": "Offline", - "default_activity_sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "event_callback_url": "", - "events_filter": null, - "friendly_name": "new", - "links": { - "activities": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities", - "statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics", - "real_time_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RealTimeStatistics", - "cumulative_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CumulativeStatistics", - "task_queues": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues", - "tasks": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks", - "workers": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers", - "workflows": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows", - "task_channels": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskChannels", - "events": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events" - }, - "multi_task_enabled": false, - "prioritize_queue_order": "FIFO", - "sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "timeout_activity_name": "Offline", - "timeout_activity_sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces.create(friendly_name="friendly_name") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/taskrouter/v1/workspace/__init__.py b/tests/integration/taskrouter/v1/workspace/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/taskrouter/v1/workspace/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/taskrouter/v1/workspace/task/__init__.py b/tests/integration/taskrouter/v1/workspace/task/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/taskrouter/v1/workspace/task/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/taskrouter/v1/workspace/task/test_reservation.py b/tests/integration/taskrouter/v1/workspace/task/test_reservation.py deleted file mode 100644 index 756006b265..0000000000 --- a/tests/integration/taskrouter/v1/workspace/task/test_reservation.py +++ /dev/null @@ -1,182 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ReservationTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks(sid="WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .reservations.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Reservations', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations?PageSize=50&Page=0", - "key": "reservations", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations?PageSize=50&Page=0" - }, - "reservations": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2014-05-14T10:50:02Z", - "date_updated": "2014-05-15T16:03:42Z", - "links": { - "task": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "worker": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "reservation_status": "accepted", - "sid": "WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_sid": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations/WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "worker_name": "Doug", - "worker_sid": "WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks(sid="WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .reservations.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations?PageSize=50&Page=0", - "key": "reservations", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations?PageSize=50&Page=0" - }, - "reservations": [] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks(sid="WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .reservations.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks(sid="WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .reservations(sid="WRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Reservations/WRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2014-05-14T10:50:02Z", - "date_updated": "2014-05-15T16:03:42Z", - "links": { - "task": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "worker": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "reservation_status": "accepted", - "sid": "WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_sid": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations/WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "worker_name": "Doug", - "worker_sid": "WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks(sid="WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .reservations(sid="WRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks(sid="WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .reservations(sid="WRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Reservations/WRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2014-05-14T10:50:02Z", - "date_updated": "2014-05-15T16:03:42Z", - "links": { - "task": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "worker": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "reservation_status": "accepted", - "sid": "WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_sid": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations/WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "worker_name": "Doug", - "worker_sid": "WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks(sid="WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .reservations(sid="WRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/taskrouter/v1/workspace/task_queue/__init__.py b/tests/integration/taskrouter/v1/workspace/task_queue/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/taskrouter/v1/workspace/task_queue/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/taskrouter/v1/workspace/task_queue/test_task_queue_cumulative_statistics.py b/tests/integration/taskrouter/v1/workspace/task_queue/test_task_queue_cumulative_statistics.py deleted file mode 100644 index 42e8259b4c..0000000000 --- a/tests/integration/taskrouter/v1/workspace/task_queue/test_task_queue_cumulative_statistics.py +++ /dev/null @@ -1,95 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class TaskQueueCumulativeStatisticsTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues(sid="WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .cumulative_statistics().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/TaskQueues/WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/CumulativeStatistics', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "reservations_created": 100, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reservations_rejected": 100, - "tasks_completed": 100, - "end_time": "2015-07-30T20:00:00Z", - "tasks_entered": 100, - "tasks_canceled": 100, - "reservations_accepted": 100, - "task_queue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reservations_timed_out": 100, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CumulativeStatistics", - "wait_duration_until_canceled": { - "avg": 0, - "min": 0, - "max": 0, - "total": 0 - }, - "wait_duration_until_accepted": { - "avg": 0, - "min": 0, - "max": 0, - "total": 0 - }, - "split_by_wait_time": { - "5": { - "above": { - "tasks_canceled": 0, - "reservations_accepted": 0 - }, - "below": { - "tasks_canceled": 0, - "reservations_accepted": 0 - } - }, - "10": { - "above": { - "tasks_canceled": 0, - "reservations_accepted": 0 - }, - "below": { - "tasks_canceled": 0, - "reservations_accepted": 0 - } - } - }, - "start_time": "2015-07-30T20:00:00Z", - "tasks_moved": 100, - "reservations_canceled": 100, - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "tasks_deleted": 100, - "reservations_rescinded": 100, - "avg_task_acceptance_time": 100 - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues(sid="WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .cumulative_statistics().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/taskrouter/v1/workspace/task_queue/test_task_queue_real_time_statistics.py b/tests/integration/taskrouter/v1/workspace/task_queue/test_task_queue_real_time_statistics.py deleted file mode 100644 index 24a8e8d103..0000000000 --- a/tests/integration/taskrouter/v1/workspace/task_queue/test_task_queue_real_time_statistics.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class TaskQueueRealTimeStatisticsTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues(sid="WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .real_time_statistics().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/TaskQueues/WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/RealTimeStatistics', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "longest_task_waiting_age": 100, - "task_queue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "tasks_by_status": { - "reserved": 0, - "pending": 0, - "assigned": 0, - "wrapping": 0 - }, - "total_eligible_workers": 100, - "activity_statistics": [ - { - "friendly_name": "Idle", - "workers": 0, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "friendly_name": "Busy", - "workers": 9, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "friendly_name": "Offline", - "workers": 6, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "friendly_name": "Reserved", - "workers": 0, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "tasks_by_priority": {}, - "total_tasks": 100, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "total_available_workers": 100, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RealTimeStatistics" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues(sid="WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .real_time_statistics().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/taskrouter/v1/workspace/task_queue/test_task_queue_statistics.py b/tests/integration/taskrouter/v1/workspace/task_queue/test_task_queue_statistics.py deleted file mode 100644 index 1abfa007f1..0000000000 --- a/tests/integration/taskrouter/v1/workspace/task_queue/test_task_queue_statistics.py +++ /dev/null @@ -1,107 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class TaskQueueStatisticsTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues(sid="WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .statistics().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/TaskQueues/WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Statistics', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics", - "cumulative": { - "avg_task_acceptance_time": 0.0, - "end_time": "2015-08-18T08:42:34Z", - "reservations_accepted": 0, - "reservations_canceled": 0, - "reservations_created": 0, - "reservations_rejected": 0, - "reservations_rescinded": 0, - "reservations_timed_out": 0, - "start_time": "2015-08-18T08:27:34Z", - "tasks_canceled": 0, - "tasks_deleted": 0, - "tasks_entered": 0, - "tasks_moved": 0 - }, - "realtime": { - "activity_statistics": [ - { - "friendly_name": "Offline", - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workers": 0 - }, - { - "friendly_name": "Idle", - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workers": 0 - }, - { - "friendly_name": "80fa2beb-3a05-11e5-8fc8-98e0d9a1eb73", - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workers": 0 - }, - { - "friendly_name": "Reserved", - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workers": 0 - }, - { - "friendly_name": "Busy", - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workers": 0 - }, - { - "friendly_name": "817ca1c5-3a05-11e5-9292-98e0d9a1eb73", - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workers": 0 - } - ], - "longest_task_waiting_age": 0, - "longest_task_waiting_sid": null, - "tasks_by_status": { - "assigned": 0, - "pending": 0, - "reserved": 0, - "wrapping": 0 - }, - "total_available_workers": 0, - "total_eligible_workers": 0, - "total_tasks": 0 - }, - "task_queue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues(sid="WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .statistics().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/taskrouter/v1/workspace/task_queue/test_task_queues_statistics.py b/tests/integration/taskrouter/v1/workspace/task_queue/test_task_queues_statistics.py deleted file mode 100644 index 0039d9ba04..0000000000 --- a/tests/integration/taskrouter/v1/workspace/task_queue/test_task_queues_statistics.py +++ /dev/null @@ -1,144 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class TaskQueuesStatisticsTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues \ - .statistics.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/TaskQueues/Statistics', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/Statistics?PageSize=50&Page=0", - "key": "task_queues_statistics", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/Statistics?PageSize=50&Page=0" - }, - "task_queues_statistics": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "cumulative": { - "avg_task_acceptance_time": 0.0, - "end_time": "2015-08-18T08:46:15Z", - "reservations_accepted": 0, - "reservations_canceled": 0, - "reservations_created": 0, - "reservations_rejected": 0, - "reservations_rescinded": 0, - "reservations_timed_out": 0, - "start_time": "2015-08-18T08:31:15Z", - "tasks_canceled": 0, - "tasks_deleted": 0, - "tasks_entered": 0, - "tasks_moved": 0 - }, - "realtime": { - "activity_statistics": [ - { - "friendly_name": "Offline", - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workers": 0 - }, - { - "friendly_name": "Idle", - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workers": 0 - }, - { - "friendly_name": "80fa2beb-3a05-11e5-8fc8-98e0d9a1eb73", - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workers": 0 - }, - { - "friendly_name": "Reserved", - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workers": 0 - }, - { - "friendly_name": "Busy", - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workers": 0 - }, - { - "friendly_name": "817ca1c5-3a05-11e5-9292-98e0d9a1eb73", - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workers": 0 - } - ], - "longest_task_waiting_age": 0, - "longest_task_waiting_sid": null, - "tasks_by_status": { - "assigned": 0, - "pending": 0, - "reserved": 0, - "wrapping": 0 - }, - "total_available_workers": 0, - "total_eligible_workers": 0, - "total_tasks": 0 - }, - "task_queue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues \ - .statistics.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/Statistics?PageSize=50&Page=0", - "key": "task_queues_statistics", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/Statistics?PageSize=50&Page=0" - }, - "task_queues_statistics": [] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues \ - .statistics.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/taskrouter/v1/workspace/test_activity.py b/tests/integration/taskrouter/v1/workspace/test_activity.py deleted file mode 100644 index 2cccd22782..0000000000 --- a/tests/integration/taskrouter/v1/workspace/test_activity.py +++ /dev/null @@ -1,216 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ActivityTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .activities(sid="WAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Activities/WAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "available": true, - "date_created": "2014-05-14T10:50:02Z", - "date_updated": "2014-05-14T23:26:06Z", - "friendly_name": "New Activity", - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities/WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .activities(sid="WAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .activities(sid="WAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Activities/WAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "available": true, - "date_created": "2014-05-14T10:50:02Z", - "date_updated": "2014-05-14T23:26:06Z", - "friendly_name": "New Activity", - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities/WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .activities(sid="WAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .activities(sid="WAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Activities/WAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .activities(sid="WAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .activities.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Activities', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "activities": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "available": true, - "date_created": "2014-05-14T10:50:02Z", - "date_updated": "2014-05-14T23:26:06Z", - "friendly_name": "New Activity", - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities/WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities?PageSize=50&Page=0", - "key": "activities", - "last_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities?PageSize=50&Page=0", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .activities.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "activities": [], - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities?PageSize=50&Page=0", - "key": "activities", - "last_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities?PageSize=50&Page=0", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .activities.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .activities.create(friendly_name="friendly_name") - - values = {'FriendlyName': "friendly_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Activities', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "available": true, - "date_created": "2014-05-14T10:50:02Z", - "date_updated": "2014-05-14T23:26:06Z", - "friendly_name": "New Activity", - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities/WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .activities.create(friendly_name="friendly_name") - - self.assertIsNotNone(actual) diff --git a/tests/integration/taskrouter/v1/workspace/test_event.py b/tests/integration/taskrouter/v1/workspace/test_event.py deleted file mode 100644 index 2418656b57..0000000000 --- a/tests/integration/taskrouter/v1/workspace/test_event.py +++ /dev/null @@ -1,152 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class EventTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .events(sid="EVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Events/EVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "actor_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "actor_type": "workspace", - "actor_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "description": "Worker JustinWorker updated to Idle Activity", - "event_data": { - "worker_activity_name": "Offline", - "worker_activity_sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "worker_attributes": "{}", - "worker_name": "JustinWorker", - "worker_sid": "WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "worker_time_in_previous_activity": "26", - "workspace_name": "WorkspaceName", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "event_date": "2015-02-07T00:32:41Z", - "event_type": "worker.activity", - "resource_sid": "WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "resource_type": "worker", - "resource_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "EVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "source": "twilio", - "source_ip_address": "1.2.3.4", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events/EVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .events(sid="EVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .events.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Events', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "events": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "actor_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "actor_type": "workspace", - "actor_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "description": "Worker JustinWorker updated to Idle Activity", - "event_data": { - "worker_activity_name": "Offline", - "worker_activity_sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "worker_attributes": "{}", - "worker_name": "JustinWorker", - "worker_sid": "WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "worker_time_in_previous_activity": "26", - "workspace_name": "WorkspaceName", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "event_date": "2015-02-07T00:32:41Z", - "event_type": "worker.activity", - "resource_sid": "WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "resource_type": "worker", - "resource_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "EVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "source": "twilio", - "source_ip_address": "1.2.3.4", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events/EVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events?PageSize=50&Page=0", - "key": "events", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .events.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "events": [], - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events?PageSize=50&Page=0", - "key": "events", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .events.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/taskrouter/v1/workspace/test_task.py b/tests/integration/taskrouter/v1/workspace/test_task.py deleted file mode 100644 index e37dccd726..0000000000 --- a/tests/integration/taskrouter/v1/workspace/test_task.py +++ /dev/null @@ -1,303 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class TaskTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks(sid="WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "age": 25200, - "assignment_status": "pending", - "attributes": "{\\"body\\": \\"hello\\"}", - "date_created": "2014-05-14T18:50:02Z", - "date_updated": "2014-05-15T07:26:06Z", - "priority": 0, - "reason": "Test Reason", - "sid": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_queue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_channel_sid": "TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_channel_unique_name": "task-channel", - "timeout": 60, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workflow_sid": "WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workflow_friendly_name": "Test Workflow", - "task_queue_friendly_name": "Test Queue", - "addons": "{}", - "links": { - "task_queue": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workflow": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows/WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reservations": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations" - } - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks(sid="WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks(sid="WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "age": 25200, - "assignment_status": "pending", - "attributes": "{\\"body\\": \\"hello\\"}", - "date_created": "2014-05-14T18:50:02Z", - "date_updated": "2014-05-15T07:26:06Z", - "priority": 0, - "reason": "Test Reason", - "sid": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_queue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_channel_sid": "TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_channel_unique_name": "task-channel", - "timeout": 60, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workflow_sid": "WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workflow_friendly_name": "Test Workflow", - "task_queue_friendly_name": "Test Queue", - "addons": "{}", - "links": { - "task_queue": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workflow": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows/WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reservations": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations" - } - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks(sid="WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks(sid="WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks(sid="WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks?PageSize=50&Page=0", - "key": "tasks", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks?PageSize=50&Page=0" - }, - "tasks": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "age": 25200, - "assignment_status": "pending", - "attributes": "{\\"body\\": \\"hello\\"}", - "date_created": "2014-05-14T14:26:54Z", - "date_updated": "2014-05-15T16:03:42Z", - "priority": 0, - "reason": "Test Reason", - "sid": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_queue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_channel_sid": "TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_channel_unique_name": "task-channel", - "timeout": 60, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workflow_sid": "WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workflow_friendly_name": "Test Workflow", - "task_queue_friendly_name": "Test Queue", - "addons": "{}", - "links": { - "task_queue": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workflow": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows/WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reservations": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations" - } - } - ] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks?PageSize=50&Page=0", - "key": "tasks", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks?PageSize=50&Page=0" - }, - "tasks": [] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks.list() - - self.assertIsNotNone(actual) - - def test_read_assignment_status_multiple_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks?PageSize=50&Page=0", - "key": "tasks", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks?PageSize=50&Page=0" - }, - "tasks": [] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "age": 25200, - "assignment_status": "pending", - "attributes": "{\\"body\\": \\"attributes\\"}", - "date_created": "2014-05-14T18:50:02Z", - "date_updated": "2014-05-15T07:26:06Z", - "priority": 1, - "reason": "Test Reason", - "sid": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_queue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_channel_sid": "TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_channel_unique_name": "unique", - "timeout": 60, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workflow_sid": "WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workflow_friendly_name": "Example Workflow", - "task_queue_friendly_name": "Example Task Queue", - "addons": "{}", - "links": { - "task_queue": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workflow": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows/WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reservations": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations" - } - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks.create() - - self.assertIsNotNone(actual) diff --git a/tests/integration/taskrouter/v1/workspace/test_task_channel.py b/tests/integration/taskrouter/v1/workspace/test_task_channel.py deleted file mode 100644 index df73649c1a..0000000000 --- a/tests/integration/taskrouter/v1/workspace/test_task_channel.py +++ /dev/null @@ -1,122 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class TaskChannelTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_channels(sid="TCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/TaskChannels/TCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2014-05-14T10:50:02Z", - "date_updated": "2014-05-14T23:26:06Z", - "friendly_name": "Default", - "sid": "TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "default", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskChannels/TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_channels(sid="TCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_channels.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/TaskChannels', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "channels": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2014-05-14T10:50:02Z", - "date_updated": "2014-05-14T23:26:06Z", - "friendly_name": "Default", - "sid": "TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "default", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskChannels/TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskChannels?PageSize=50&Page=0", - "key": "channels", - "last_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskChannels?PageSize=50&Page=0", - "next_page_url": null, - "page": 0, - "page_size": 1, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskChannels?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_channels.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "channels": [], - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskChannels?PageSize=50&Page=0", - "key": "channels", - "last_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskChannels?PageSize=50&Page=0", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskChannels?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_channels.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/taskrouter/v1/workspace/test_task_queue.py b/tests/integration/taskrouter/v1/workspace/test_task_queue.py deleted file mode 100644 index 9ff0020a16..0000000000 --- a/tests/integration/taskrouter/v1/workspace/test_task_queue.py +++ /dev/null @@ -1,278 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class TaskQueueTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues(sid="WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/TaskQueues/WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assignment_activity_name": "817ca1c5-3a05-11e5-9292-98e0d9a1eb73", - "assignment_activity_sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-08-04T01:31:41Z", - "date_updated": "2015-08-04T01:31:41Z", - "friendly_name": "81f96435-3a05-11e5-9f81-98e0d9a1eb73", - "max_reserved_workers": 1, - "links": { - "assignment_activity": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities/WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reservation_activity": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities/WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics", - "real_time_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RealTimeStatistics", - "cumulative_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CumulativeStatistics", - "list_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/Statistics" - }, - "reservation_activity_name": "80fa2beb-3a05-11e5-8fc8-98e0d9a1eb73", - "reservation_activity_sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "target_workers": null, - "task_order": "FIFO", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues(sid="WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues(sid="WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/TaskQueues/WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assignment_activity_name": "817ca1c5-3a05-11e5-9292-98e0d9a1eb73", - "assignment_activity_sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-08-04T01:31:41Z", - "date_updated": "2015-08-04T01:31:41Z", - "friendly_name": "81f96435-3a05-11e5-9f81-98e0d9a1eb73", - "max_reserved_workers": 1, - "links": { - "assignment_activity": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities/WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reservation_activity": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities/WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics", - "real_time_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RealTimeStatistics", - "cumulative_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CumulativeStatistics", - "list_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/Statistics" - }, - "reservation_activity_name": "80fa2beb-3a05-11e5-8fc8-98e0d9a1eb73", - "reservation_activity_sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "target_workers": null, - "task_order": "FIFO", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues(sid="WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/TaskQueues', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues?PageSize=50&Page=0", - "key": "task_queues", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues?PageSize=50&Page=0" - }, - "task_queues": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assignment_activity_name": "817ca1c5-3a05-11e5-9292-98e0d9a1eb73", - "assignment_activity_sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-08-04T01:31:41Z", - "date_updated": "2015-08-04T01:31:41Z", - "friendly_name": "81f96435-3a05-11e5-9f81-98e0d9a1eb73", - "max_reserved_workers": 1, - "links": { - "assignment_activity": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities/WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reservation_activity": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities/WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics", - "real_time_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RealTimeStatistics", - "cumulative_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CumulativeStatistics", - "list_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/Statistics" - }, - "reservation_activity_name": "80fa2beb-3a05-11e5-8fc8-98e0d9a1eb73", - "reservation_activity_sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "target_workers": null, - "task_order": "FIFO", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues?PageSize=50&Page=0", - "key": "task_queues", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues?PageSize=50&Page=0" - }, - "task_queues": [] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues.create(friendly_name="friendly_name", reservation_activity_sid="WAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", assignment_activity_sid="WAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = { - 'FriendlyName': "friendly_name", - 'ReservationActivitySid': "WAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", - 'AssignmentActivitySid': "WAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", - } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/TaskQueues', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assignment_activity_name": "817ca1c5-3a05-11e5-9292-98e0d9a1eb73", - "assignment_activity_sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-08-04T01:31:41Z", - "date_updated": "2015-08-04T01:31:41Z", - "friendly_name": "81f96435-3a05-11e5-9f81-98e0d9a1eb73", - "max_reserved_workers": 1, - "links": { - "assignment_activity": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities/WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reservation_activity": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities/WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics", - "real_time_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RealTimeStatistics", - "cumulative_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CumulativeStatistics", - "list_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/Statistics" - }, - "reservation_activity_name": "80fa2beb-3a05-11e5-8fc8-98e0d9a1eb73", - "reservation_activity_sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "target_workers": null, - "task_order": "FIFO", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues.create(friendly_name="friendly_name", reservation_activity_sid="WAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", assignment_activity_sid="WAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues(sid="WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/TaskQueues/WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues(sid="WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/taskrouter/v1/workspace/test_worker.py b/tests/integration/taskrouter/v1/workspace/test_worker.py deleted file mode 100644 index 319ca810ef..0000000000 --- a/tests/integration/taskrouter/v1/workspace/test_worker.py +++ /dev/null @@ -1,274 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class WorkerTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Workers', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers?PageSize=50&Page=0", - "next_page_url": null, - "key": "workers" - }, - "workers": [ - { - "sid": "WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "testWorker", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "activity_sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "activity_name": "Offline", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "attributes": "{}", - "available": false, - "date_created": "2017-05-30T23:05:29Z", - "date_updated": "2017-05-30T23:05:29Z", - "date_status_changed": "2017-05-30T23:05:29Z", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "channels": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels", - "activity": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities/WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/Statistics", - "real_time_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/RealTimeStatistics", - "cumulative_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/CumulativeStatistics", - "worker_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics", - "worker_channels": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels", - "reservations": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations" - } - } - ] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers?PageSize=50&Page=0", - "key": "workers", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers?PageSize=50&Page=0" - }, - "workers": [] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers.create(friendly_name="friendly_name") - - values = {'FriendlyName': "friendly_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Workers', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "NewWorker", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "activity_sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "activity_name": "Offline", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "attributes": "{}", - "available": false, - "date_created": "2017-05-30T23:19:38Z", - "date_updated": "2017-05-30T23:19:38Z", - "date_status_changed": "2017-05-30T23:19:38Z", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "channels": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels", - "activity": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities/WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/Statistics", - "real_time_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/RealTimeStatistics", - "cumulative_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/CumulativeStatistics", - "worker_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics", - "worker_channels": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels", - "reservations": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations" - } - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers.create(friendly_name="friendly_name") - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Workers/WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "activity_name": "available", - "activity_sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "attributes": "{}", - "available": false, - "date_created": "2017-05-30T23:32:39Z", - "date_status_changed": "2017-05-30T23:32:39Z", - "date_updated": "2017-05-30T23:32:39Z", - "friendly_name": "NewWorker3", - "sid": "WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "channels": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels", - "activity": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities/WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/Statistics", - "real_time_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/RealTimeStatistics", - "cumulative_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/CumulativeStatistics", - "worker_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics", - "worker_channels": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels", - "reservations": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations" - } - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Workers/WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "blah", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "activity_sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "activity_name": "Offline", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "attributes": "{}", - "available": false, - "date_created": "2017-05-30T23:32:22Z", - "date_updated": "2017-05-31T00:05:57Z", - "date_status_changed": "2017-05-30T23:32:22Z", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "channels": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels", - "activity": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Activities/WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/Statistics", - "real_time_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/RealTimeStatistics", - "cumulative_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/CumulativeStatistics", - "worker_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics", - "worker_channels": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels", - "reservations": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations" - } - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Workers/WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/taskrouter/v1/workspace/test_workflow.py b/tests/integration/taskrouter/v1/workspace/test_workflow.py deleted file mode 100644 index 8b89b025e0..0000000000 --- a/tests/integration/taskrouter/v1/workspace/test_workflow.py +++ /dev/null @@ -1,252 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class WorkflowTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows(sid="WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Workflows/WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assignment_callback_url": "http://example.com", - "configuration": "task-routing:\\n - filter: \\n - 1 == 1\\n target:\\n - queue: WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\n set-priority: 0\\n", - "date_created": "2014-05-14T10:50:02Z", - "date_updated": "2014-05-14T23:26:06Z", - "document_content_type": "application/json", - "fallback_assignment_callback_url": null, - "friendly_name": "Default Fifo Workflow", - "sid": "WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_reservation_timeout": 120, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows/WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows/WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics", - "real_time_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows/WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RealTimeStatistics", - "cumulative_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows/WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CumulativeStatistics" - } - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows(sid="WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows(sid="WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Workflows/WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assignment_callback_url": "http://example.com", - "configuration": "task-routing:\\n - filter: \\n - 1 == 1\\n target:\\n - queue: WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\n set-priority: 0\\n", - "date_created": "2014-05-14T10:50:02Z", - "date_updated": "2014-05-14T23:26:06Z", - "document_content_type": "application/json", - "fallback_assignment_callback_url": null, - "friendly_name": "Default Fifo Workflow", - "sid": "WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_reservation_timeout": 120, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows/WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows/WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics", - "real_time_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows/WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RealTimeStatistics", - "cumulative_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows/WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CumulativeStatistics" - }, - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows(sid="WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows(sid="WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Workflows/WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows(sid="WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Workflows', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows?PageSize=50&Page=0", - "key": "workflows", - "last_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows?PageSize=50&Page=0", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows?PageSize=50&Page=0" - }, - "workflows": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assignment_callback_url": "http://example.com", - "configuration": "task-routing:\\n - filter: \\n - 1 == 1\\n target:\\n - queue: WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\n set-priority: 0\\n", - "date_created": "2014-05-14T10:50:02Z", - "date_updated": "2014-05-15T16:47:51Z", - "document_content_type": "application/json", - "fallback_assignment_callback_url": null, - "friendly_name": "Default Fifo Workflow", - "sid": "WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_reservation_timeout": 120, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows/WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows/WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics", - "real_time_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows/WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RealTimeStatistics", - "cumulative_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows/WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CumulativeStatistics" - }, - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows?PageSize=50&Page=0", - "key": "workflows", - "last_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows?PageSize=50&Page=0", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows?PageSize=50&Page=0" - }, - "workflows": [] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows.create(friendly_name="friendly_name", configuration="configuration") - - values = {'FriendlyName': "friendly_name", 'Configuration': "configuration", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Workflows', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assignment_callback_url": "http://example.com", - "configuration": "task-routing:\\n - filter: \\n - 1 == 1\\n target:\\n - queue: WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\n set-priority: 0\\n", - "date_created": "2014-05-14T10:50:02Z", - "date_updated": "2014-05-14T23:26:06Z", - "document_content_type": "application/json", - "fallback_assignment_callback_url": null, - "friendly_name": "Default Fifo Workflow", - "sid": "WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_reservation_timeout": 120, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows/WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows/WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics", - "real_time_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows/WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RealTimeStatistics", - "cumulative_statistics": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows/WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CumulativeStatistics" - } - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows.create(friendly_name="friendly_name", configuration="configuration") - - self.assertIsNotNone(actual) diff --git a/tests/integration/taskrouter/v1/workspace/test_workspace_cumulative_statistics.py b/tests/integration/taskrouter/v1/workspace/test_workspace_cumulative_statistics.py deleted file mode 100644 index 271a2b8cfe..0000000000 --- a/tests/integration/taskrouter/v1/workspace/test_workspace_cumulative_statistics.py +++ /dev/null @@ -1,93 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class WorkspaceCumulativeStatisticsTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .cumulative_statistics().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/CumulativeStatistics', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "reservations_accepted": 100, - "tasks_completed": 100, - "start_time": "2015-07-30T20:00:00Z", - "reservations_rescinded": 100, - "tasks_timed_out_in_workflow": 100, - "end_time": "2015-07-30T20:00:00Z", - "avg_task_acceptance_time": 100, - "tasks_canceled": 100, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CumulativeStatistics", - "tasks_moved": 100, - "tasks_deleted": 100, - "tasks_created": 100, - "reservations_canceled": 100, - "reservations_timed_out": 100, - "wait_duration_until_canceled": { - "avg": 0, - "min": 0, - "max": 0, - "total": 0 - }, - "wait_duration_until_accepted": { - "avg": 0, - "min": 0, - "max": 0, - "total": 0 - }, - "split_by_wait_time": { - "5": { - "above": { - "tasks_canceled": 0, - "reservations_accepted": 0 - }, - "below": { - "tasks_canceled": 0, - "reservations_accepted": 0 - } - }, - "10": { - "above": { - "tasks_canceled": 0, - "reservations_accepted": 0 - }, - "below": { - "tasks_canceled": 0, - "reservations_accepted": 0 - } - } - }, - "reservations_created": 100, - "reservations_rejected": 100, - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .cumulative_statistics().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/taskrouter/v1/workspace/test_workspace_real_time_statistics.py b/tests/integration/taskrouter/v1/workspace/test_workspace_real_time_statistics.py deleted file mode 100644 index 9d8c3c54e3..0000000000 --- a/tests/integration/taskrouter/v1/workspace/test_workspace_real_time_statistics.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class WorkspaceRealTimeStatisticsTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .real_time_statistics().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/RealTimeStatistics', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RealTimeStatistics", - "tasks_by_priority": {}, - "activity_statistics": [ - { - "friendly_name": "Idle", - "workers": 0, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "friendly_name": "Busy", - "workers": 9, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "friendly_name": "Offline", - "workers": 6, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "friendly_name": "Reserved", - "workers": 0, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "longest_task_waiting_age": 100, - "total_workers": 100, - "total_tasks": 100, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "tasks_by_status": {} - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .real_time_statistics().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/taskrouter/v1/workspace/test_workspace_statistics.py b/tests/integration/taskrouter/v1/workspace/test_workspace_statistics.py deleted file mode 100644 index 3670823929..0000000000 --- a/tests/integration/taskrouter/v1/workspace/test_workspace_statistics.py +++ /dev/null @@ -1,104 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class WorkspaceStatisticsTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .statistics().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Statistics', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics", - "cumulative": { - "avg_task_acceptance_time": 0.0, - "start_time": "2008-01-02T00:00:00Z", - "reservations_accepted": 0, - "reservations_canceled": 0, - "reservations_created": 0, - "reservations_rejected": 0, - "reservations_rescinded": 0, - "reservations_timed_out": 0, - "end_time": "2008-01-02T00:00:00Z", - "tasks_canceled": 0, - "tasks_created": 0, - "tasks_deleted": 0, - "tasks_moved": 0, - "tasks_timed_out_in_workflow": 0 - }, - "realtime": { - "activity_statistics": [ - { - "friendly_name": "Offline", - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workers": 1 - }, - { - "friendly_name": "Idle", - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workers": 0 - }, - { - "friendly_name": "80fa2beb-3a05-11e5-8fc8-98e0d9a1eb73", - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workers": 0 - }, - { - "friendly_name": "Reserved", - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workers": 0 - }, - { - "friendly_name": "Busy", - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workers": 0 - }, - { - "friendly_name": "817ca1c5-3a05-11e5-9292-98e0d9a1eb73", - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workers": 0 - } - ], - "longest_task_waiting_age": 0, - "longest_task_waiting_sid": null, - "tasks_by_status": { - "assigned": 0, - "pending": 0, - "reserved": 0, - "wrapping": 0 - }, - "total_tasks": 0, - "total_workers": 1 - }, - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .statistics().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/taskrouter/v1/workspace/worker/__init__.py b/tests/integration/taskrouter/v1/workspace/worker/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/taskrouter/v1/workspace/worker/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/taskrouter/v1/workspace/worker/test_reservation.py b/tests/integration/taskrouter/v1/workspace/worker/test_reservation.py deleted file mode 100644 index 9fb0e59243..0000000000 --- a/tests/integration/taskrouter/v1/workspace/worker/test_reservation.py +++ /dev/null @@ -1,182 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ReservationTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .reservations.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Workers/WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Reservations', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations?PageSize=50&Page=0", - "key": "reservations", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations?PageSize=50&Page=0" - }, - "reservations": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2014-05-14T10:50:02Z", - "date_updated": "2014-05-15T16:03:42Z", - "links": { - "task": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "worker": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "reservation_status": "accepted", - "sid": "WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_sid": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations/WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "worker_name": "Doug", - "worker_sid": "WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .reservations.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations?PageSize=50&Page=0", - "key": "reservations", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations?PageSize=50&Page=0" - }, - "reservations": [] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .reservations.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .reservations(sid="WRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Workers/WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Reservations/WRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2014-05-14T10:50:02Z", - "date_updated": "2014-05-15T16:03:42Z", - "links": { - "task": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "worker": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "reservation_status": "accepted", - "sid": "WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_sid": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations/WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "worker_name": "Doug", - "worker_sid": "WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .reservations(sid="WRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .reservations(sid="WRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Workers/WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Reservations/WRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2014-05-14T10:50:02Z", - "date_updated": "2014-05-15T16:03:42Z", - "links": { - "task": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "worker": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "reservation_status": "accepted", - "sid": "WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_sid": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Reservations/WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "worker_name": "Doug", - "worker_sid": "WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .reservations(sid="WRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/taskrouter/v1/workspace/worker/test_worker_channel.py b/tests/integration/taskrouter/v1/workspace/worker/test_worker_channel.py deleted file mode 100644 index 05d0a6c2dd..0000000000 --- a/tests/integration/taskrouter/v1/workspace/worker/test_worker_channel.py +++ /dev/null @@ -1,176 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class WorkerChannelTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .worker_channels.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Workers/WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "key": "channels", - "next_page_url": null, - "page": 0, - "page_size": 1, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels" - }, - "channels": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assigned_tasks": 0, - "available": true, - "available_capacity_percentage": 100, - "configured_capacity": 1, - "date_created": "2014-05-14T10:50:02Z", - "date_updated": "2014-05-15T16:03:42Z", - "sid": "WCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_channel_sid": "TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_channel_unique_name": "default", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "worker_sid": "WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .worker_channels.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0", - "key": "channels", - "next_page_url": null, - "page": 0, - "page_size": 1, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels" - }, - "channels": [] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .worker_channels.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .worker_channels(sid="WCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Workers/WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/WCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assigned_tasks": 0, - "available": true, - "available_capacity_percentage": 100, - "configured_capacity": 1, - "date_created": "2014-05-14T10:50:02Z", - "date_updated": "2014-05-15T16:03:42Z", - "sid": "WCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_channel_sid": "TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_channel_unique_name": "default", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "worker_sid": "WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .worker_channels(sid="WCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .worker_channels(sid="WCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Workers/WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/WCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assigned_tasks": 0, - "available": true, - "available_capacity_percentage": 100, - "configured_capacity": 3, - "date_created": "2014-05-14T10:50:02Z", - "date_updated": "2014-05-15T16:03:42Z", - "sid": "WCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_channel_sid": "TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_channel_unique_name": "default", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "worker_sid": "WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .worker_channels(sid="WCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/taskrouter/v1/workspace/worker/test_worker_statistics.py b/tests/integration/taskrouter/v1/workspace/worker/test_worker_statistics.py deleted file mode 100644 index 1690b1359d..0000000000 --- a/tests/integration/taskrouter/v1/workspace/worker/test_worker_statistics.py +++ /dev/null @@ -1,91 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class WorkerStatisticsTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .statistics().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Workers/WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Statistics', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "cumulative": { - "reservations_created": 100, - "reservations_accepted": 100, - "reservations_rejected": 100, - "reservations_timed_out": 100, - "reservations_canceled": 100, - "reservations_rescinded": 100, - "activity_durations": [ - { - "max": 0, - "min": 900, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Offline", - "avg": 1080, - "total": 5400 - }, - { - "max": 0, - "min": 900, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Busy", - "avg": 1012, - "total": 8100 - }, - { - "max": 0, - "min": 0, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Idle", - "avg": 0, - "total": 0 - }, - { - "max": 0, - "min": 0, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Reserved", - "avg": 0, - "total": 0 - } - ], - "start_time": "2008-01-02T00:00:00Z", - "end_time": "2008-01-02T00:00:00Z" - }, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "worker_sid": "WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .statistics().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/taskrouter/v1/workspace/worker/test_workers_cumulative_statistics.py b/tests/integration/taskrouter/v1/workspace/worker/test_workers_cumulative_statistics.py deleted file mode 100644 index 15b1a170d7..0000000000 --- a/tests/integration/taskrouter/v1/workspace/worker/test_workers_cumulative_statistics.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class WorkersCumulativeStatisticsTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .cumulative_statistics().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Workers/CumulativeStatistics', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/CumulativeStatistics", - "reservations_created": 100, - "reservations_accepted": 100, - "reservations_rejected": 100, - "reservations_timed_out": 100, - "reservations_canceled": 100, - "reservations_rescinded": 100, - "activity_durations": [ - { - "max": 0, - "min": 900, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Offline", - "avg": 1080, - "total": 5400 - }, - { - "max": 0, - "min": 900, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Busy", - "avg": 1012, - "total": 8100 - }, - { - "max": 0, - "min": 0, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Idle", - "avg": 0, - "total": 0 - }, - { - "max": 0, - "min": 0, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Reserved", - "avg": 0, - "total": 0 - } - ], - "start_time": "2015-07-30T20:00:00Z", - "end_time": "2015-07-30T20:00:00Z" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .cumulative_statistics().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/taskrouter/v1/workspace/worker/test_workers_real_time_statistics.py b/tests/integration/taskrouter/v1/workspace/worker/test_workers_real_time_statistics.py deleted file mode 100644 index 062c89892a..0000000000 --- a/tests/integration/taskrouter/v1/workspace/worker/test_workers_real_time_statistics.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class WorkersRealTimeStatisticsTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .real_time_statistics().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Workers/RealTimeStatistics', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/RealTimeStatistics", - "total_workers": 15, - "activity_statistics": [ - { - "friendly_name": "Idle", - "workers": 0, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "friendly_name": "Busy", - "workers": 9, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "friendly_name": "Offline", - "workers": 6, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "friendly_name": "Reserved", - "workers": 0, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers(sid="WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .real_time_statistics().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/taskrouter/v1/workspace/worker/test_workers_statistics.py b/tests/integration/taskrouter/v1/workspace/worker/test_workers_statistics.py deleted file mode 100644 index 748771ff6c..0000000000 --- a/tests/integration/taskrouter/v1/workspace/worker/test_workers_statistics.py +++ /dev/null @@ -1,115 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class WorkersStatisticsTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers \ - .statistics().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Workers/Statistics', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "cumulative": { - "reservations_created": 0, - "reservations_accepted": 0, - "reservations_rejected": 0, - "reservations_timed_out": 0, - "reservations_canceled": 0, - "reservations_rescinded": 0, - "activity_durations": [ - { - "max": 0, - "min": 900, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Offline", - "avg": 1080, - "total": 5400 - }, - { - "max": 0, - "min": 900, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Busy", - "avg": 1012, - "total": 8100 - }, - { - "max": 0, - "min": 0, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Idle", - "avg": 0, - "total": 0 - }, - { - "max": 0, - "min": 0, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Reserved", - "avg": 0, - "total": 0 - } - ], - "start_time": "2008-01-02T00:00:00Z", - "end_time": "2008-01-02T00:00:00Z" - }, - "realtime": { - "total_workers": 15, - "activity_statistics": [ - { - "friendly_name": "Idle", - "workers": 0, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "friendly_name": "Busy", - "workers": 9, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "friendly_name": "Offline", - "workers": 6, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "friendly_name": "Reserved", - "workers": 0, - "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - }, - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/Statistics" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers \ - .statistics().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/taskrouter/v1/workspace/workflow/__init__.py b/tests/integration/taskrouter/v1/workspace/workflow/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/taskrouter/v1/workspace/workflow/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/taskrouter/v1/workspace/workflow/test_workflow_cumulative_statistics.py b/tests/integration/taskrouter/v1/workspace/workflow/test_workflow_cumulative_statistics.py deleted file mode 100644 index 5edabe5e4e..0000000000 --- a/tests/integration/taskrouter/v1/workspace/workflow/test_workflow_cumulative_statistics.py +++ /dev/null @@ -1,96 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class WorkflowCumulativeStatisticsTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows(sid="WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .cumulative_statistics().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Workflows/WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/CumulativeStatistics', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "avg_task_acceptance_time": 100, - "tasks_canceled": 100, - "start_time": "2015-07-30T20:00:00Z", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "tasks_moved": 100, - "tasks_entered": 100, - "wait_duration_until_canceled": { - "avg": 0, - "min": 0, - "max": 0, - "total": 0 - }, - "wait_duration_until_accepted": { - "avg": 0, - "min": 0, - "max": 0, - "total": 0 - }, - "split_by_wait_time": { - "5": { - "above": { - "tasks_canceled": 0, - "reservations_accepted": 0 - }, - "below": { - "tasks_canceled": 0, - "reservations_accepted": 0 - } - }, - "10": { - "above": { - "tasks_canceled": 0, - "reservations_accepted": 0 - }, - "below": { - "tasks_canceled": 0, - "reservations_accepted": 0 - } - } - }, - "reservations_canceled": 100, - "end_time": "2015-07-30T20:00:00Z", - "workflow_sid": "WWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reservations_created": 100, - "reservations_accepted": 100, - "reservations_rescinded": 100, - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reservations_rejected": 100, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows/WWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CumulativeStatistics", - "tasks_deleted": 100, - "tasks_timed_out_in_workflow": 100, - "tasks_completed": 100, - "reservations_timed_out": 100 - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows(sid="WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .cumulative_statistics().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/taskrouter/v1/workspace/workflow/test_workflow_real_time_statistics.py b/tests/integration/taskrouter/v1/workspace/workflow/test_workflow_real_time_statistics.py deleted file mode 100644 index b96da4c498..0000000000 --- a/tests/integration/taskrouter/v1/workspace/workflow/test_workflow_real_time_statistics.py +++ /dev/null @@ -1,56 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class WorkflowRealTimeStatisticsTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows(sid="WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .real_time_statistics().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Workflows/WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/RealTimeStatistics', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "longest_task_waiting_age": 100, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows/WWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RealTimeStatistics", - "tasks_by_priority": {}, - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "tasks_by_status": { - "reserved": 0, - "pending": 0, - "assigned": 0, - "wrapping": 0 - }, - "workflow_sid": "WWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "total_tasks": 100, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows(sid="WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .real_time_statistics().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/taskrouter/v1/workspace/workflow/test_workflow_statistics.py b/tests/integration/taskrouter/v1/workspace/workflow/test_workflow_statistics.py deleted file mode 100644 index ba870e9771..0000000000 --- a/tests/integration/taskrouter/v1/workspace/workflow/test_workflow_statistics.py +++ /dev/null @@ -1,70 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class WorkflowStatisticsTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows(sid="WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .statistics().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Workflows/WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Statistics', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows/WWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics", - "cumulative": { - "avg_task_acceptance_time": 0.0, - "end_time": "2008-01-02T00:00:00Z", - "reservations_accepted": 0, - "reservations_rejected": 0, - "reservations_timed_out": 0, - "start_time": "2008-01-02T00:00:00Z", - "tasks_canceled": 0, - "tasks_entered": 0, - "tasks_moved": 0, - "tasks_timed_out_in_workflow": 0 - }, - "realtime": { - "longest_task_waiting_age": 0, - "longest_task_waiting_sid": null, - "tasks_by_status": { - "assigned": 1, - "pending": 0, - "reserved": 0, - "wrapping": 0 - }, - "total_tasks": 1 - }, - "workflow_sid": "WWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows(sid="WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .statistics().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/trunking/__init__.py b/tests/integration/trunking/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/trunking/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/trunking/v1/__init__.py b/tests/integration/trunking/v1/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/trunking/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/trunking/v1/test_trunk.py b/tests/integration/trunking/v1/test_trunk.py deleted file mode 100644 index 4717115c24..0000000000 --- a/tests/integration/trunking/v1/test_trunk.py +++ /dev/null @@ -1,256 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class TrunkTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "domain_name": "test.pstn.twilio.com", - "disaster_recovery_method": "POST", - "disaster_recovery_url": "http://disaster-recovery.com", - "friendly_name": "friendly_name", - "secure": false, - "recording": { - "mode": "do-not-record", - "trim": "do-not-trim" - }, - "auth_type": "", - "auth_type_set": [], - "date_created": "2015-01-02T11:23:45Z", - "date_updated": "2015-01-02T11:23:45Z", - "url": "http://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "origination_urls": "http://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls", - "credential_lists": "http://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists", - "ip_access_control_lists": "http://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists", - "phone_numbers": "http://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers" - } - } - ''' - )) - - actual = self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://trunking.twilio.com/v1/Trunks', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "domain_name": "test.pstn.twilio.com", - "disaster_recovery_method": "POST", - "disaster_recovery_url": "http://disaster-recovery.com", - "friendly_name": "friendly_name", - "secure": false, - "recording": { - "mode": "do-not-record", - "trim": "do-not-trim" - }, - "auth_type": "", - "auth_type_set": [], - "date_created": "2015-01-02T11:23:45Z", - "date_updated": "2015-01-02T11:23:45Z", - "url": "http://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "origination_urls": "http://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls", - "credential_lists": "http://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists", - "ip_access_control_lists": "http://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists", - "phone_numbers": "http://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers" - } - } - ''' - )) - - actual = self.client.trunking.v1.trunks.create() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://trunking.twilio.com/v1/Trunks?PageSize=1&Page=0", - "key": "trunks", - "next_page_url": null, - "page": 0, - "page_size": 1, - "previous_page_url": null, - "url": "https://trunking.twilio.com/v1/Trunks?PageSize=1&Page=0" - }, - "trunks": [ - { - "sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "domain_name": "test.pstn.twilio.com", - "disaster_recovery_method": "POST", - "disaster_recovery_url": "http://disaster-recovery.com", - "friendly_name": "friendly_name", - "secure": false, - "recording": { - "mode": "do-not-record", - "trim": "do-not-trim" - }, - "auth_type": "", - "auth_type_set": [], - "date_created": "2015-01-02T11:23:45Z", - "date_updated": "2015-01-02T11:23:45Z", - "url": "http://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "origination_urls": "http://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls", - "credential_lists": "http://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists", - "ip_access_control_lists": "http://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists", - "phone_numbers": "http://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers" - } - } - ] - } - ''' - )) - - actual = self.client.trunking.v1.trunks.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://trunking.twilio.com/v1/Trunks?PageSize=1&Page=0", - "key": "trunks", - "next_page_url": null, - "page": 0, - "page_size": 1, - "previous_page_url": null, - "url": "https://trunking.twilio.com/v1/Trunks?PageSize=1&Page=0" - }, - "trunks": [] - } - ''' - )) - - actual = self.client.trunking.v1.trunks.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "domain_name": "test.pstn.twilio.com", - "disaster_recovery_method": "GET", - "disaster_recovery_url": "http://updated-recovery.com", - "friendly_name": "updated_name", - "secure": true, - "recording": { - "mode": "do-not-record", - "trim": "do-not-trim" - }, - "auth_type": "", - "auth_type_set": [], - "date_created": "2015-01-02T11:23:45Z", - "date_updated": "2015-01-02T11:23:45Z", - "url": "http://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "origination_urls": "http://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls", - "credential_lists": "http://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists", - "ip_access_control_lists": "http://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists", - "phone_numbers": "http://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers" - } - } - ''' - )) - - actual = self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/trunking/v1/trunk/__init__.py b/tests/integration/trunking/v1/trunk/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/trunking/v1/trunk/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/trunking/v1/trunk/test_credential_list.py b/tests/integration/trunking/v1/trunk/test_credential_list.py deleted file mode 100644 index a8bb7d91af..0000000000 --- a/tests/integration/trunking/v1/trunk/test_credential_list.py +++ /dev/null @@ -1,177 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class CredentialListTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials_lists(sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/CredentialLists/CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "trunk_sid": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Wed, 11 Sep 2013 17:51:38 -0000", - "date_updated": "Wed, 11 Sep 2013 17:51:38 -0000", - "friendly_name": "Low Rises", - "sid": "CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials_lists(sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials_lists(sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/CredentialLists/CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials_lists(sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials_lists.create(credential_list_sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = {'CredentialListSid': "CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/CredentialLists', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "trunk_sid": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Wed, 11 Sep 2013 17:51:38 -0000", - "date_updated": "Wed, 11 Sep 2013 17:51:38 -0000", - "friendly_name": "Low Rises", - "sid": "CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials_lists.create(credential_list_sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials_lists.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/CredentialLists', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "credential_lists": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "trunk_sid": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Wed, 11 Sep 2013 17:51:38 -0000", - "date_updated": "Wed, 11 Sep 2013 17:51:38 -0000", - "friendly_name": "Low Rises", - "sid": "CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists?PageSize=50&Page=0", - "next_page_url": null, - "key": "credential_lists" - } - } - ''' - )) - - actual = self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials_lists.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "credential_lists": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists?PageSize=50&Page=0", - "next_page_url": null, - "key": "credential_lists" - } - } - ''' - )) - - actual = self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials_lists.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/trunking/v1/trunk/test_ip_access_control_list.py b/tests/integration/trunking/v1/trunk/test_ip_access_control_list.py deleted file mode 100644 index e4df4c8226..0000000000 --- a/tests/integration/trunking/v1/trunk/test_ip_access_control_list.py +++ /dev/null @@ -1,177 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class IpAccessControlListTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_lists(sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IpAccessControlLists/ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "trunk_sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "http://www.example.com" - } - ''' - )) - - actual = self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_lists(sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_lists(sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IpAccessControlLists/ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_lists(sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_lists.create(ip_access_control_list_sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = {'IpAccessControlListSid': "ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IpAccessControlLists', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "trunk_sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "http://www.example.com" - } - ''' - )) - - actual = self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_lists.create(ip_access_control_list_sid="ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_lists.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IpAccessControlLists', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "ip_access_control_lists": [], - "meta": { - "first_page_url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists?Page=0&PageSize=50", - "key": "ip_access_control_lists", - "next_page_url": null, - "page": 0, - "page_size": 0, - "previous_page_url": null, - "url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists" - } - } - ''' - )) - - actual = self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_lists.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "ip_access_control_lists": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "trunk_sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "http://www.example.com" - } - ], - "meta": { - "first_page_url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists?Page=0&PageSize=50", - "key": "ip_access_control_lists", - "next_page_url": null, - "page": 0, - "page_size": 1, - "previous_page_url": null, - "url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists" - } - } - ''' - )) - - actual = self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_lists.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/trunking/v1/trunk/test_origination_url.py b/tests/integration/trunking/v1/trunk/test_origination_url.py deleted file mode 100644 index 845ffe8e3c..0000000000 --- a/tests/integration/trunking/v1/trunk/test_origination_url.py +++ /dev/null @@ -1,232 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class OriginationUrlTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls(sid="OUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/OriginationUrls/OUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "weight": 1, - "date_updated": "2015-01-02T11:23:45Z", - "enabled": true, - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "priority": 1, - "sip_url": "sip://sip-box.com:1234", - "sid": "OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-01-02T11:23:45Z", - "trunk_sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls/OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls(sid="OUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls(sid="OUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/OriginationUrls/OUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls(sid="OUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls.create(weight=1, priority=1, enabled=True, friendly_name="friendly_name", sip_url="https://example.com") - - values = { - 'Weight': 1, - 'Priority': 1, - 'Enabled': True, - 'FriendlyName': "friendly_name", - 'SipUrl': "https://example.com", - } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/OriginationUrls', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "weight": 1, - "date_updated": "2015-01-02T11:23:45Z", - "enabled": true, - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "priority": 1, - "sip_url": "sip://sip-box.com:1234", - "sid": "OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-01-02T11:23:45Z", - "trunk_sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls/OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls.create(weight=1, priority=1, enabled=True, friendly_name="friendly_name", sip_url="https://example.com") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/OriginationUrls', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls?PageSize=1&Page=0", - "key": "origination_urls", - "next_page_url": null, - "page": 0, - "page_size": 1, - "previous_page_url": null, - "url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls?PageSize=1&Page=0" - }, - "origination_urls": [ - { - "weight": 1, - "date_updated": "2015-01-02T11:23:45Z", - "enabled": true, - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "priority": 1, - "sip_url": "sip://sip-box.com:1234", - "sid": "OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-01-02T11:23:45Z", - "trunk_sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls/OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls?PageSize=1&Page=0", - "key": "origination_urls", - "next_page_url": null, - "page": 0, - "page_size": 1, - "previous_page_url": null, - "url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls?PageSize=1&Page=0" - }, - "origination_urls": [] - } - ''' - )) - - actual = self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls(sid="OUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/OriginationUrls/OUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "weight": 2, - "date_updated": "2015-01-02T11:23:45Z", - "enabled": false, - "friendly_name": "updated_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "priority": 2, - "sip_url": "sip://sip-updated.com:4321", - "sid": "OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-01-02T11:23:45Z", - "trunk_sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls/OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls(sid="OUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/trunking/v1/trunk/test_phone_number.py b/tests/integration/trunking/v1/trunk/test_phone_number.py deleted file mode 100644 index 055830aa56..0000000000 --- a/tests/integration/trunking/v1/trunk/test_phone_number.py +++ /dev/null @@ -1,252 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class PhoneNumberTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/PhoneNumbers/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2010-12-10T17:27:34Z", - "date_updated": "2015-10-09T11:36:32Z", - "friendly_name": "(415) 867-5309", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "phone_number": "+14158675309", - "api_version": "2010-04-01", - "voice_caller_id_lookup": null, - "voice_url": "", - "voice_method": "POST", - "voice_fallback_url": null, - "voice_fallback_method": null, - "status_callback": "", - "status_callback_method": "POST", - "voice_application_sid": null, - "trunk_sid": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sms_url": "", - "sms_method": "POST", - "sms_fallback_url": "", - "sms_fallback_method": "POST", - "sms_application_sid": "", - "address_requirements": "none", - "beta": false, - "url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "capabilities": { - "voice": true, - "sms": true, - "mms": true - }, - "links": { - "phone_number": "https://api.twilio.com/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - } - ''' - )) - - actual = self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/PhoneNumbers/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers(sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers.create(phone_number_sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = {'PhoneNumberSid': "PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/PhoneNumbers', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2010-12-10T17:27:34Z", - "date_updated": "2015-10-09T11:36:32Z", - "friendly_name": "(415) 867-5309", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "phone_number": "+14158675309", - "api_version": "2010-04-01", - "voice_caller_id_lookup": null, - "voice_url": "", - "voice_method": "POST", - "voice_fallback_url": null, - "voice_fallback_method": null, - "status_callback": "", - "status_callback_method": "POST", - "voice_application_sid": null, - "trunk_sid": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sms_url": "", - "sms_method": "POST", - "sms_fallback_url": "", - "sms_fallback_method": "POST", - "sms_application_sid": "", - "address_requirements": "none", - "beta": false, - "url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "capabilities": { - "voice": true, - "sms": true, - "mms": true - }, - "links": { - "phone_number": "https://api.twilio.com/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - } - ''' - )) - - actual = self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers.create(phone_number_sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/PhoneNumbers', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers?PageSize=1&Page=0", - "key": "phone_numbers", - "next_page_url": null, - "page": 0, - "page_size": 1, - "previous_page_url": null, - "url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers?PageSize=1&Page=0" - }, - "phone_numbers": [ - { - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2010-12-10T17:27:34Z", - "date_updated": "2015-10-09T11:36:32Z", - "friendly_name": "(415) 867-5309", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "phone_number": "+14158675309", - "api_version": "2010-04-01", - "voice_caller_id_lookup": null, - "voice_url": "", - "voice_method": "POST", - "voice_fallback_url": null, - "voice_fallback_method": null, - "status_callback": "", - "status_callback_method": "POST", - "voice_application_sid": null, - "trunk_sid": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sms_url": "", - "sms_method": "POST", - "sms_fallback_url": "", - "sms_fallback_method": "POST", - "sms_application_sid": "", - "address_requirements": "none", - "beta": false, - "url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "capabilities": { - "voice": true, - "sms": true, - "mms": true - }, - "links": { - "phone_number": "https://api.twilio.com/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - } - ] - } - ''' - )) - - actual = self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers?PageSize=1&Page=0", - "key": "phone_numbers", - "next_page_url": null, - "page": 0, - "page_size": 1, - "previous_page_url": null, - "url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers?PageSize=1&Page=0" - }, - "phone_numbers": [] - } - ''' - )) - - actual = self.client.trunking.v1.trunks(sid="TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/video/__init__.py b/tests/integration/video/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/video/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/video/v1/__init__.py b/tests/integration/video/v1/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/video/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/video/v1/room/__init__.py b/tests/integration/video/v1/room/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/video/v1/room/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/video/v1/room/room_participant/__init__.py b/tests/integration/video/v1/room/room_participant/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/video/v1/room/room_participant/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/video/v1/room/room_participant/test_room_participant_published_track.py b/tests/integration/video/v1/room/room_participant/test_room_participant_published_track.py deleted file mode 100644 index e055e0629e..0000000000 --- a/tests/integration/video/v1/room/room_participant/test_room_participant_published_track.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class PublishedTrackTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.rooms(sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .published_tracks(sid="MTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://video.twilio.com/v1/Rooms/RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/PublishedTracks/MTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "room_sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "participant_sid": "PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "MTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "name": "bob-track", - "kind": "data", - "enabled": true, - "url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PublishedTracks/MTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.video.v1.rooms(sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .published_tracks(sid="MTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.rooms(sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .published_tracks.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://video.twilio.com/v1/Rooms/RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/PublishedTracks', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "published_tracks": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PublishedTracks?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PublishedTracks?PageSize=50&Page=0", - "next_page_url": null, - "key": "published_tracks" - } - } - ''' - )) - - actual = self.client.video.v1.rooms(sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .published_tracks.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/video/v1/room/room_participant/test_room_participant_subscribed_track.py b/tests/integration/video/v1/room/room_participant/test_room_participant_subscribed_track.py deleted file mode 100644 index 23d51bff5b..0000000000 --- a/tests/integration/video/v1/room/room_participant/test_room_participant_subscribed_track.py +++ /dev/null @@ -1,127 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class SubscribedTrackTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.rooms(sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .subscribed_tracks.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://video.twilio.com/v1/Rooms/RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SubscribedTracks', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "subscribed_tracks": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SubscribedTracks?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SubscribedTracks?PageSize=50&Page=0", - "next_page_url": null, - "key": "subscribed_tracks" - } - } - ''' - )) - - actual = self.client.video.v1.rooms(sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .subscribed_tracks.list() - - self.assertIsNotNone(actual) - - def test_read_filters_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "subscribed_tracks": [ - { - "publisher_sid": "PAbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - "subscriber_sid": "PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "room_sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "sid": "MTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "name": "bob-track", - "kind": "data", - "enabled": true - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SubscribedTracks?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SubscribedTracks?PageSize=50&Page=0", - "next_page_url": null, - "key": "subscribed_tracks" - } - } - ''' - )) - - actual = self.client.video.v1.rooms(sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .subscribed_tracks.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.rooms(sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .subscribed_tracks.update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://video.twilio.com/v1/Rooms/RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SubscribedTracks', - )) - - def test_update_filters_response(self): - self.holodeck.mock(Response( - 202, - ''' - { - "publisher_sid": null, - "subscriber_sid": "PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "room_sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": null, - "date_updated": null, - "sid": null, - "name": "bob-track", - "kind": "data", - "enabled": null - } - ''' - )) - - actual = self.client.video.v1.rooms(sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .subscribed_tracks.update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/video/v1/room/test_recording.py b/tests/integration/video/v1/room/test_recording.py deleted file mode 100644 index 0dac33a41a..0000000000 --- a/tests/integration/video/v1/room/test_recording.py +++ /dev/null @@ -1,141 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class RoomRecordingTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.rooms(sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="RTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://video.twilio.com/v1/Rooms/RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings/RTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "processing", - "date_created": "2015-07-30T20:00:00Z", - "sid": "RTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "source_sid": "MTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "size": 0, - "type": "audio", - "duration": 0, - "container_format": "mka", - "codec": "OPUS", - "grouping_sids": { - "room_sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "room_sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/RTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "media": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/RTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media" - } - } - ''' - )) - - actual = self.client.video.v1.rooms(sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings(sid="RTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.rooms(sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://video.twilio.com/v1/Rooms/RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "recordings": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings?PageSize=50&Page=0", - "next_page_url": null, - "key": "recordings" - } - } - ''' - )) - - actual = self.client.video.v1.rooms(sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings.list() - - self.assertIsNotNone(actual) - - def test_read_results_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "recordings": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "completed", - "date_created": "2015-07-30T20:00:00Z", - "sid": "RTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "source_sid": "MTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "size": 23, - "type": "audio", - "duration": 10, - "container_format": "mka", - "codec": "OPUS", - "grouping_sids": { - "room_sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "participant_sid": "PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "room_sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/RTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "media": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/RTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media" - } - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings?PageSize=50&Page=0", - "next_page_url": null, - "key": "recordings" - } - } - ''' - )) - - actual = self.client.video.v1.rooms(sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/video/v1/room/test_room_participant.py b/tests/integration/video/v1/room/test_room_participant.py deleted file mode 100644 index daef7b4fa4..0000000000 --- a/tests/integration/video/v1/room/test_room_participant.py +++ /dev/null @@ -1,175 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class ParticipantTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.rooms(sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://video.twilio.com/v1/Rooms/RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "room_sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "start_time": "2015-07-30T20:00:00Z", - "end_time": null, - "sid": "PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "bob", - "status": "connected", - "url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "duration": null, - "links": { - "published_tracks": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PublishedTracks", - "subscribed_tracks": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SubscribedTracks" - } - } - ''' - )) - - actual = self.client.video.v1.rooms(sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.rooms(sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://video.twilio.com/v1/Rooms/RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "participants": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants?PageSize=50&Page=0", - "next_page_url": null, - "key": "participants" - } - } - ''' - )) - - actual = self.client.video.v1.rooms(sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.list() - - self.assertIsNotNone(actual) - - def test_read_filters_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "participants": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "room_sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2017-07-30T20:00:00Z", - "date_updated": "2017-07-30T20:00:00Z", - "start_time": "2017-07-30T20:00:00Z", - "end_time": "2017-07-30T20:00:01Z", - "sid": "PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "alice", - "status": "disconnected", - "url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "duration": 1, - "links": { - "published_tracks": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PublishedTracks", - "subscribed_tracks": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SubscribedTracks" - } - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants?PageSize=50&Page=0", - "next_page_url": null, - "key": "participants" - } - } - ''' - )) - - actual = self.client.video.v1.rooms(sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.rooms(sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://video.twilio.com/v1/Rooms/RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "room_sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2017-07-30T20:00:00Z", - "date_updated": "2017-07-30T20:00:00Z", - "start_time": "2017-07-30T20:00:00Z", - "end_time": "2017-07-30T20:00:01Z", - "sid": "PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "alice", - "status": "disconnected", - "url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "duration": 1, - "links": { - "published_tracks": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PublishedTracks", - "subscribed_tracks": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SubscribedTracks" - } - } - ''' - )) - - actual = self.client.video.v1.rooms(sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants(sid="PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/video/v1/test_composition.py b/tests/integration/video/v1/test_composition.py deleted file mode 100644 index 455af28109..0000000000 --- a/tests/integration/video/v1/test_composition.py +++ /dev/null @@ -1,211 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class CompositionTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.compositions(sid="CJXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://video.twilio.com/v1/Compositions/CJXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "completed", - "date_created": "2015-07-30T20:00:00Z", - "date_completed": "2015-07-30T20:01:33Z", - "date_deleted": null, - "sid": "CJaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "audio_sources": [ - "RTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - ], - "video_sources": [ - "RTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - ], - "video_layout": "GRID", - "resolution": "1280x720", - "format": "webm", - "bitrate": 64, - "size": 4, - "duration": 6, - "room_sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://video.twilio.com/v1/Compositions/CJaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "media": "https://video.twilio.com/v1/Compositions/CJaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media" - } - } - ''' - )) - - actual = self.client.video.v1.compositions(sid="CJXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.compositions.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://video.twilio.com/v1/Compositions', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "compositions": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://video.twilio.com/v1/Compositions?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://video.twilio.com/v1/Compositions?PageSize=50&Page=0", - "next_page_url": null, - "key": "compositions" - } - } - ''' - )) - - actual = self.client.video.v1.compositions.list() - - self.assertIsNotNone(actual) - - def test_read_results_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "compositions": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "completed", - "date_created": "2015-07-30T20:00:00Z", - "date_completed": "2015-07-30T20:01:33Z", - "date_deleted": null, - "sid": "CJaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "audio_sources": [ - "RTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "RTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab" - ], - "video_sources": [], - "video_layout": "GRID", - "resolution": "1280x720", - "format": "mp3", - "bitrate": 16, - "size": 55, - "duration": 10, - "room_sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://video.twilio.com/v1/Compositions/CJaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "media": "https://video.twilio.com/v1/Compositions/CJaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media" - } - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://video.twilio.com/v1/Compositions?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://video.twilio.com/v1/Compositions?PageSize=50&Page=0", - "next_page_url": null, - "key": "compositions" - } - } - ''' - )) - - actual = self.client.video.v1.compositions.list() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.compositions(sid="CJXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://video.twilio.com/v1/Compositions/CJXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.video.v1.compositions(sid="CJXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.compositions.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://video.twilio.com/v1/Compositions', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "processing", - "date_created": "2015-07-30T20:00:00Z", - "date_completed": null, - "date_deleted": null, - "sid": "CJaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "audio_sources": [ - "RTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "RTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab" - ], - "video_sources": [], - "video_layout": "GRID", - "resolution": "1280x720", - "format": "mp3", - "bitrate": 0, - "size": 0, - "duration": 1, - "room_sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://video.twilio.com/v1/Compositions/CJaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "media": "https://video.twilio.com/v1/Compositions/CJaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media" - } - } - ''' - )) - - actual = self.client.video.v1.compositions.create() - - self.assertIsNotNone(actual) diff --git a/tests/integration/video/v1/test_recording.py b/tests/integration/video/v1/test_recording.py deleted file mode 100644 index 83e6b20716..0000000000 --- a/tests/integration/video/v1/test_recording.py +++ /dev/null @@ -1,165 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class RecordingTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.recordings(sid="RTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://video.twilio.com/v1/Recordings/RTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "processing", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T21:00:00Z", - "date_deleted": "2015-07-30T22:00:00Z", - "sid": "RTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "source_sid": "MTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "size": 0, - "url": "https://video.twilio.com/v1/Recordings/RTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "type": "audio", - "duration": 0, - "container_format": "mka", - "codec": "OPUS", - "track_name": "A name", - "grouping_sids": { - "room_sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "media_external_location": "https://my-super-duper-bucket.s3.amazonaws.com/my/path/", - "encryption_key": "public_key", - "links": { - "media": "https://video.twilio.com/v1/Recordings/RTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media" - } - } - ''' - )) - - actual = self.client.video.v1.recordings(sid="RTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.recordings.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://video.twilio.com/v1/Recordings', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "recordings": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://video.twilio.com/v1/Recordings?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://video.twilio.com/v1/Recordings?PageSize=50&Page=0", - "next_page_url": null, - "key": "recordings" - } - } - ''' - )) - - actual = self.client.video.v1.recordings.list() - - self.assertIsNotNone(actual) - - def test_read_results_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "recordings": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "completed", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T21:00:00Z", - "date_deleted": "2015-07-30T22:00:00Z", - "sid": "RTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "source_sid": "MTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "size": 23, - "type": "audio", - "duration": 10, - "container_format": "mka", - "codec": "OPUS", - "track_name": "A name", - "grouping_sids": { - "room_sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "participant_sid": "PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "media_external_location": "https://my-super-duper-bucket.s3.amazonaws.com/my/path/", - "encryption_key": "public_key", - "url": "https://video.twilio.com/v1/Recordings/RTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "media": "https://video.twilio.com/v1/Recordings/RTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media" - } - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://video.twilio.com/v1/Recordings?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://video.twilio.com/v1/Recordings?PageSize=50&Page=0", - "next_page_url": null, - "key": "recordings" - } - } - ''' - )) - - actual = self.client.video.v1.recordings.list() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.recordings(sid="RTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://video.twilio.com/v1/Recordings/RTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.video.v1.recordings(sid="RTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/video/v1/test_room.py b/tests/integration/video/v1/test_room.py deleted file mode 100644 index 66350dc179..0000000000 --- a/tests/integration/video/v1/test_room.py +++ /dev/null @@ -1,242 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class RoomTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.rooms(sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://video.twilio.com/v1/Rooms/RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "status": "in-progress", - "type": "peer-to-peer", - "sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "enable_turn": true, - "unique_name": "unique_name", - "max_participants": 10, - "duration": 0, - "status_callback_method": "POST", - "status_callback": "", - "record_participants_on_connect": false, - "video_codecs": [ - "VP8" - ], - "media_region": "us1", - "end_time": "2015-07-30T20:00:00Z", - "url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "participants": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants", - "recordings": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings" - } - } - ''' - )) - - actual = self.client.video.v1.rooms(sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.rooms.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://video.twilio.com/v1/Rooms', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "status": "in-progress", - "type": "peer-to-peer", - "sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "enable_turn": true, - "unique_name": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "max_participants": 10, - "duration": 0, - "status_callback_method": "POST", - "status_callback": "", - "record_participants_on_connect": false, - "video_codecs": [ - "VP8" - ], - "media_region": "us1", - "end_time": "2015-07-30T20:00:00Z", - "url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "participants": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants", - "recordings": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings" - } - } - ''' - )) - - actual = self.client.video.v1.rooms.create() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.rooms.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://video.twilio.com/v1/Rooms', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "rooms": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://video.twilio.com/v1/Rooms?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://video.twilio.com/v1/Rooms?PageSize=50&Page=0", - "next_page_url": null, - "key": "rooms" - } - } - ''' - )) - - actual = self.client.video.v1.rooms.list() - - self.assertIsNotNone(actual) - - def test_read_with_status_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "rooms": [ - { - "sid": "RM4070b618362c1682b2385b1f9982833c", - "status": "completed", - "date_created": "2017-04-03T22:21:49Z", - "date_updated": "2017-04-03T22:21:51Z", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "type": "peer-to-peer", - "enable_turn": true, - "unique_name": "RM4070b618362c1682b2385b1f9982833c", - "status_callback": null, - "status_callback_method": "POST", - "end_time": "2017-04-03T22:21:51Z", - "duration": 2, - "max_participants": 10, - "record_participants_on_connect": false, - "video_codecs": [ - "VP8" - ], - "media_region": "us1", - "url": "https://video.twilio.com/v1/Rooms/RM4070b618362c1682b2385b1f9982833c", - "links": { - "participants": "https://video.twilio.com/v1/Rooms/RM4070b618362c1682b2385b1f9982833c/Participants", - "recordings": "https://video.twilio.com/v1/Rooms/RM4070b618362c1682b2385b1f9982833c/Recordings" - } - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://video.twilio.com/v1/Rooms?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://video.twilio.com/v1/Rooms?PageSize=50&Page=0", - "next_page_url": null, - "key": "rooms" - } - } - ''' - )) - - actual = self.client.video.v1.rooms.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.rooms(sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(status="in-progress") - - values = {'Status': "in-progress", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://video.twilio.com/v1/Rooms/RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "status": "completed", - "type": "peer-to-peer", - "sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "enable_turn": true, - "unique_name": "unique_name", - "max_participants": 10, - "status_callback_method": "POST", - "status_callback": "", - "record_participants_on_connect": false, - "video_codecs": [ - "VP8" - ], - "media_region": "us1", - "end_time": "2015-07-30T20:00:00Z", - "duration": 10, - "url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "participants": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants", - "recordings": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings" - } - } - ''' - )) - - actual = self.client.video.v1.rooms(sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(status="in-progress") - - self.assertIsNotNone(actual) diff --git a/tests/integration/wireless/__init__.py b/tests/integration/wireless/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/wireless/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/wireless/v1/__init__.py b/tests/integration/wireless/v1/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/wireless/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/wireless/v1/sim/__init__.py b/tests/integration/wireless/v1/sim/__init__.py deleted file mode 100644 index f58a79e4d6..0000000000 --- a/tests/integration/wireless/v1/sim/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/wireless/v1/sim/test_data_session.py b/tests/integration/wireless/v1/sim/test_data_session.py deleted file mode 100644 index 7c14426f3e..0000000000 --- a/tests/integration/wireless/v1/sim/test_data_session.py +++ /dev/null @@ -1,86 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class DataSessionTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.wireless.v1.sims(sid="DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .data_sessions.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://wireless.twilio.com/v1/Sims/DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/DataSessions', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "data_sessions": [ - { - "sid": "WNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sim_sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "radio_link": "LTE", - "operator_mcc": "", - "operator_mnc": "", - "operator_country": "", - "operator_name": "", - "cell_id": "", - "cell_location_estimate": {}, - "packets_uploaded": 0, - "packets_downloaded": 0, - "last_updated": "2015-07-30T20:00:00Z", - "start": "2015-07-30T20:00:00Z", - "end": null - }, - { - "sid": "WNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sim_sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "radio_link": "3G", - "operator_mcc": "", - "operator_mnc": "", - "operator_country": "", - "operator_name": "", - "cell_id": "", - "cell_location_estimate": {}, - "packets_uploaded": 0, - "packets_downloaded": 0, - "last_updated": "2015-07-30T20:00:00Z", - "start": "2015-07-30T20:00:00Z", - "end": "2015-07-30T20:00:00Z" - } - ], - "meta": { - "first_page_url": "https://wireless.twilio.com/v1/Sims/DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DataSessions?PageSize=50&Page=0", - "key": "data_sessions", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://wireless.twilio.com/v1/Sims/DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DataSessions?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.wireless.v1.sims(sid="DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .data_sessions.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/wireless/v1/sim/test_usage_record.py b/tests/integration/wireless/v1/sim/test_usage_record.py deleted file mode 100644 index b32464bcf6..0000000000 --- a/tests/integration/wireless/v1/sim/test_usage_record.py +++ /dev/null @@ -1,66 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class UsageRecordTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.wireless.v1.sims(sid="DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage_records.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://wireless.twilio.com/v1/Sims/DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/UsageRecords', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "usage_records": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "commands": {}, - "data": {}, - "sim_sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "period": {} - }, - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "commands": {}, - "data": {}, - "sim_sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "period": {} - } - ], - "meta": { - "first_page_url": "https://wireless.twilio.com/v1/Sims/DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/UsageRecords?PageSize=50&Page=0", - "key": "usage_records", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://wireless.twilio.com/v1/Sims/DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/UsageRecords?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.wireless.v1.sims(sid="DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage_records.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/wireless/v1/test_command.py b/tests/integration/wireless/v1/test_command.py deleted file mode 100644 index c4dae39faa..0000000000 --- a/tests/integration/wireless/v1/test_command.py +++ /dev/null @@ -1,156 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class CommandTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.wireless.v1.commands(sid="DCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://wireless.twilio.com/v1/Commands/DCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "command": "command", - "command_mode": "text", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "sim_sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "direction": "from_sim", - "sid": "DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "queued", - "url": "https://wireless.twilio.com/v1/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.wireless.v1.commands(sid="DCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.wireless.v1.commands.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://wireless.twilio.com/v1/Commands', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "commands": [], - "meta": { - "first_page_url": "https://wireless.twilio.com/v1/Commands?PageSize=50&Page=0", - "key": "commands", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://wireless.twilio.com/v1/Commands?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.wireless.v1.commands.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "commands": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "command": "command", - "command_mode": "text", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "sim_sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "direction": "from_sim", - "sid": "DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "queued", - "url": "https://wireless.twilio.com/v1/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://wireless.twilio.com/v1/Commands?PageSize=50&Page=0", - "key": "commands", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://wireless.twilio.com/v1/Commands?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.wireless.v1.commands.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.wireless.v1.commands.create(command="command") - - values = {'Command': "command", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://wireless.twilio.com/v1/Commands', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "command": "command", - "command_mode": "text", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "sim_sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "direction": "from_sim", - "sid": "DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "queued", - "url": "https://wireless.twilio.com/v1/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.wireless.v1.commands.create(command="command") - - self.assertIsNotNone(actual) diff --git a/tests/integration/wireless/v1/test_rate_plan.py b/tests/integration/wireless/v1/test_rate_plan.py deleted file mode 100644 index f132160e27..0000000000 --- a/tests/integration/wireless/v1/test_rate_plan.py +++ /dev/null @@ -1,248 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class RatePlanTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.wireless.v1.rate_plans.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://wireless.twilio.com/v1/RatePlans', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://wireless.twilio.com/v1/RatePlans?PageSize=50&Page=0", - "key": "rate_plans", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://wireless.twilio.com/v1/RatePlans?PageSize=50&Page=0" - }, - "rate_plans": [] - } - ''' - )) - - actual = self.client.wireless.v1.rate_plans.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://wireless.twilio.com/v1/RatePlans?PageSize=50&Page=0", - "key": "rate_plans", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://wireless.twilio.com/v1/RatePlans?PageSize=50&Page=0" - }, - "rate_plans": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "data_enabled": true, - "data_limit": 1000, - "data_metering": "pooled", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "messaging_enabled": true, - "voice_enabled": true, - "national_roaming_enabled": true, - "national_roaming_data_limit": 1000, - "international_roaming": [ - "data", - "messaging", - "voice" - ], - "international_roaming_data_limit": 1000, - "sid": "WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://wireless.twilio.com/v1/RatePlans/WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.wireless.v1.rate_plans.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.wireless.v1.rate_plans(sid="WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://wireless.twilio.com/v1/RatePlans/WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "data_enabled": true, - "data_limit": 1000, - "data_metering": "pooled", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "messaging_enabled": true, - "voice_enabled": true, - "national_roaming_enabled": true, - "national_roaming_data_limit": 1000, - "international_roaming": [ - "data", - "messaging", - "voice" - ], - "international_roaming_data_limit": 1000, - "sid": "WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://wireless.twilio.com/v1/RatePlans/WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.wireless.v1.rate_plans(sid="WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.wireless.v1.rate_plans.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://wireless.twilio.com/v1/RatePlans', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "data_enabled": true, - "data_limit": 1000, - "data_metering": "pooled", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "messaging_enabled": true, - "voice_enabled": true, - "national_roaming_enabled": true, - "national_roaming_data_limit": 1000, - "international_roaming": [ - "data", - "messaging", - "voice" - ], - "international_roaming_data_limit": 1000, - "sid": "WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://wireless.twilio.com/v1/RatePlans/WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.wireless.v1.rate_plans.create() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.wireless.v1.rate_plans(sid="WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://wireless.twilio.com/v1/RatePlans/WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "data_enabled": true, - "data_limit": 1000, - "data_metering": "pooled", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "messaging_enabled": true, - "voice_enabled": true, - "national_roaming_enabled": true, - "national_roaming_data_limit": 1000, - "international_roaming": [ - "data", - "messaging", - "voice" - ], - "international_roaming_data_limit": 1000, - "sid": "WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://wireless.twilio.com/v1/RatePlans/WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.wireless.v1.rate_plans(sid="WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.wireless.v1.rate_plans(sid="WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://wireless.twilio.com/v1/RatePlans/WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.wireless.v1.rate_plans(sid="WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/wireless/v1/test_sim.py b/tests/integration/wireless/v1/test_sim.py deleted file mode 100644 index 2a3f77c127..0000000000 --- a/tests/integration/wireless/v1/test_sim.py +++ /dev/null @@ -1,204 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from tests import IntegrationTestCase -from tests.holodeck import Request -from twilio.base.exceptions import TwilioException -from twilio.http.response import Response - - -class SimTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.wireless.v1.sims(sid="DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://wireless.twilio.com/v1/Sims/DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "commands_callback_method": "http_method", - "commands_callback_url": "http://www.example.com", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "sms_fallback_method": "http_method", - "sms_fallback_url": "http://www.example.com", - "sms_method": "http_method", - "sms_url": "http://www.example.com", - "voice_fallback_method": "http_method", - "voice_fallback_url": "http://www.example.com", - "voice_method": "http_method", - "voice_url": "http://www.example.com", - "links": { - "data_sessions": "https://wireless.twilio.com/v1/Sims/DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DataSessions", - "rate_plan": "https://wireless.twilio.com/v1/RatePlans/WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "usage_records": "https://wireless.twilio.com/v1/Sims/DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/UsageRecords" - }, - "rate_plan_sid": "WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "iccid": "iccid", - "e_id": "e_id", - "status": "new", - "url": "https://wireless.twilio.com/v1/Sims/DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ip_address": "192.168.1.1" - } - ''' - )) - - actual = self.client.wireless.v1.sims(sid="DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.wireless.v1.sims.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://wireless.twilio.com/v1/Sims', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sims": [], - "meta": { - "first_page_url": "https://wireless.twilio.com/v1/Sims?PageSize=50&Page=0", - "key": "sims", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://wireless.twilio.com/v1/Sims?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.wireless.v1.sims.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sims": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "commands_callback_method": "http_method", - "commands_callback_url": "http://www.example.com", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "links": { - "data_sessions": "https://wireless.twilio.com/v1/Sims/DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DataSessions", - "rate_plan": "https://wireless.twilio.com/v1/RatePlans/WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "usage_records": "https://wireless.twilio.com/v1/Sims/DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/UsageRecords" - }, - "rate_plan_sid": "WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "iccid": "iccid", - "e_id": "e_id", - "status": "new", - "sms_fallback_method": "http_method", - "sms_fallback_url": "http://www.example.com", - "sms_method": "http_method", - "sms_url": "http://www.example.com", - "voice_fallback_method": "http_method", - "voice_fallback_url": "http://www.example.com", - "voice_method": "http_method", - "voice_url": "http://www.example.com", - "url": "https://wireless.twilio.com/v1/Sims/DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ip_address": "192.168.1.30" - } - ], - "meta": { - "first_page_url": "https://wireless.twilio.com/v1/Sims?PageSize=50&Page=0", - "key": "sims", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://wireless.twilio.com/v1/Sims?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.wireless.v1.sims.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.wireless.v1.sims(sid="DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://wireless.twilio.com/v1/Sims/DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "commands_callback_method": "http_method", - "commands_callback_url": "http://www.example.com", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "links": { - "data_sessions": "https://wireless.twilio.com/v1/Sims/DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DataSessions", - "rate_plan": "https://wireless.twilio.com/v1/RatePlans/WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "usage_records": "https://wireless.twilio.com/v1/Sims/DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/UsageRecords" - }, - "rate_plan_sid": "WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "iccid": "iccid", - "e_id": "e_id", - "status": "new", - "sms_fallback_method": "http_method", - "sms_fallback_url": "http://www.example.com", - "sms_method": "http_method", - "sms_url": "http://www.example.com", - "voice_fallback_method": "http_method", - "voice_fallback_url": "http://www.example.com", - "voice_method": "http_method", - "voice_url": "http://www.example.com", - "url": "https://wireless.twilio.com/v1/Sims/DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ip_address": "192.168.1.30" - } - ''' - )) - - actual = self.client.wireless.v1.sims(sid="DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/requirements.txt b/tests/requirements.txt index 3d13d6baa0..679f8e13d0 100644 --- a/tests/requirements.txt +++ b/tests/requirements.txt @@ -1,10 +1,14 @@ -sphinx==1.4.9 -mock==0.8.0 -nose -coverage -nosexcover +Sphinx>=1.8.0 +mock +pytest +pytest-cov +aiounittest flake8 -mccabe wheel>=0.22.0 cryptography -twine +recommonmark +django +multidict +pyngrok +black +autoflake 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 index 93d5092f1c..33f627e838 100644 --- a/tests/unit/base/test_deserialize.py +++ b/tests/unit/base/test_deserialize.py @@ -2,51 +2,46 @@ import unittest from decimal import Decimal -import pytz - from twilio.base import deserialize class Iso8601DateTestCase(unittest.TestCase): - def test_parsable(self): - actual = deserialize.iso8601_date('2015-01-02') + 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) + 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, pytz.utc) + 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) + 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('')) + self.assertEqual("", deserialize.decimal("")) def test_zero_string(self): - self.assertEqual(Decimal('0.0000'), deserialize.decimal('0.0000')) + self.assertEqual(Decimal("0.0000"), deserialize.decimal("0.0000")) def test_negative_string(self): - self.assertEqual(Decimal('-0.0123'), deserialize.decimal('-0.0123')) + self.assertEqual(Decimal("-0.0123"), deserialize.decimal("-0.0123")) def test_positive_string(self): - self.assertEqual(Decimal('0.0123'), deserialize.decimal('0.0123')) + self.assertEqual(Decimal("0.0123"), deserialize.decimal("0.0123")) def test_zero(self): self.assertEqual(0, deserialize.decimal(0)) @@ -59,21 +54,20 @@ def test_positive(self): class IntegerTestCase(unittest.TestCase): - def test_none(self): self.assertEqual(None, deserialize.integer(None)) def test_empty_string(self): - self.assertEqual('', deserialize.integer('')) + self.assertEqual("", deserialize.integer("")) def test_zero_string(self): - self.assertEqual(0, deserialize.integer('0')) + self.assertEqual(0, deserialize.integer("0")) def test_negative_string(self): - self.assertEqual(-1, deserialize.integer('-1')) + self.assertEqual(-1, deserialize.integer("-1")) def test_positive_string(self): - self.assertEqual(1, deserialize.integer('1')) + self.assertEqual(1, deserialize.integer("1")) def test_zero(self): self.assertEqual(0, deserialize.integer(0)) @@ -83,7 +77,3 @@ def test_negative(self): 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 index d27d4707b2..57891a65b7 100644 --- a/tests/unit/base/test_serialize.py +++ b/tests/unit/base/test_serialize.py @@ -5,7 +5,6 @@ class Iso8601DateTestCase(unittest.TestCase): - def test_unset(self): value = values.unset actual = serialize.iso8601_date(value) @@ -14,25 +13,24 @@ def test_unset(self): 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) + 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) + 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) + self.assertEqual("2015-01-02", actual) def test_str(self): - actual = serialize.iso8601_date('2015-01-02') - self.assertEqual('2015-01-02', actual) + 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) @@ -41,81 +39,86 @@ def test_unset(self): 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) + 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) + 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) + 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) + 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') + 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) + 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) + 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' + 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", }, - 'foo': 'bar' - } - actual = serialize.prefixed_collapsible_map(value, 'Prefix') - self.assertEqual({ - 'Prefix.watson.language': 'en', - 'Prefix.watson.alice': 'bob', - 'Prefix.foo': 'bar' - }, actual) + actual, + ) def test_list(self): - value = [ - 'foo', - 'bar' - ] - actual = serialize.prefixed_collapsible_map(value, 'Prefix') + 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'}) + actual = serialize.object({"twilio": "rocks"}) self.assertEqual('{"twilio": "rocks"}', actual) def test_list(self): - actual = serialize.object(['twilio', 'rocks']) + actual = serialize.object(["twilio", "rocks"]) self.assertEqual('["twilio", "rocks"]', actual) def test_does_not_change_other_types(self): @@ -135,5 +138,5 @@ def test_does_not_change_other_types(self): 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) + 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/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 index c5c79d243a..8484e57b17 100644 --- a/tests/unit/http/test_http_client.py +++ b/tests/unit/http/test_http_client.py @@ -1,27 +1,26 @@ # -*- coding: utf-8 -*- - -import six - +import os import unittest +from collections import OrderedDict -import mock -from mock import patch, Mock -from requests import Request +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_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.session_mock.send.return_value = Response(200, "testing-unicode: Ω≈ç√, 💩") self.request_mock.headers = {} session_constructor_mock = self.session_patcher.start() @@ -33,62 +32,227 @@ 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.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) - self.client.request('doesnt matter', 'doesnt matter') + 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 - self.assertEqual('other.twilio.com', self.request_mock.headers['Host']) - self.assertIsNotNone(self.client.last_request) - self.assertIsNotNone(self.client.last_response) + 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'} + self.request_mock.url = "https://api.twilio.com/" + self.request_mock.headers = {"Host": "other.twilio.com"} - response = self.client.request('doesnt matter', 'doesnt matter') + response = self.client.request("doesnt matter", "doesnt matter") - self.assertEqual('other.twilio.com', self.request_mock.headers['Host']) + self.assertEqual("other.twilio.com", self.request_mock.headers["Host"]) self.assertEqual(200, response.status_code) - self.assertEqual('testing-unicode: Ω≈ç√, 💩', response.content) + 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.last_request) - self.assertEqual('doesnt-matter-url', self.client.last_request.url) - self.assertEqual('DOESNT-MATTER-METHOD', self.client.last_request.method) - self.assertEqual({'params-value': 'params-key'}, self.client.last_request.params) - self.assertEqual({'data-value': 'data-key'}, self.client.last_request.data) - self.assertEqual({'headers-value': 'headers-key'}, self.client.last_request.headers) - self.assertEqual(['a', 'b'], self.client.last_request.auth) - - self.assertIsNotNone(self.client.last_response) - self.assertEqual(200, self.client.last_response.status_code) - self.assertEqual('testing-unicode: Ω≈ç√, 💩', self.client.last_response.text) + 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') + self.session_mock.send.side_effect = Exception("voltron") with self.assertRaises(Exception): - self.client.request('doesnt-matter', 'doesnt-matter') - - self.assertIsNotNone(self.client.last_request) - self.assertIsNone(self.client.last_response) + 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_patcher = patch("twilio.http.http_client.Session") self.session_constructor_mock = self.session_patcher.start() def tearDown(self): @@ -96,34 +260,40 @@ def tearDown(self): def _setup_session_response(self, value): session_mock = Mock(wraps=Session()) - request_mock = Mock() + 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') + self._setup_session_response("response_1") client = TwilioHttpClient() - response_1 = client.request('GET', 'https://api.twilio.com') + response_1 = client.request("GET", "https://api.twilio.com") - self._setup_session_response('response_2') - response_2 = 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') + 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') + self._setup_session_response("response_1") client = TwilioHttpClient(pool_connections=False) - response_1 = client.request('GET', 'https://api.twilio.com') + response_1 = client.request("GET", "https://api.twilio.com") - self._setup_session_response('response_2') - response_2 = 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') + 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 index c8ab1969fd..5fdd4cb9fc 100644 --- a/tests/unit/http/test_validation_client.py +++ b/tests/unit/http/test_validation_client.py @@ -2,11 +2,11 @@ import unittest -import mock 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 @@ -14,108 +14,131 @@ class TestValidationClientHelpers(unittest.TestCase): def setUp(self): self.request = Request( - 'GET', - 'https://api.twilio.com/2010-04-01/Accounts/AC123/Messages', - auth=('Username', 'Password'), + "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') + 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) + 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 + '?QueryParam=1&Other=true' + 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) + 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): - self.request.body = 'foobar' + 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) + 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): - self.request.body = 'foobar' - self.request.url = self.request.url + '?QueryParam=Value&OtherQueryParam=OtherValue' + 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) + 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)) + 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_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.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') + 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.request_mock.url = "https://api.twilio.com/" - self.client.request('doesnt matter', 'doesnt matter') + 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']) + 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.request_mock.url = "https://api.twilio.com/" + self.request_mock.headers = {"Host": "other.twilio.com"} - self.client.request('doesnt matter', 'doesnt matter') + 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("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'} + self.request_mock.url = "https://api.twilio.com/" + self.request_mock.headers = {"Host": "other.twilio.com"} - response = self.client.request('doesnt matter', 'doesnt matter') + 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("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) + 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/test_access_token.py b/tests/unit/jwt/test_access_token.py index d863304b3d..7f1e908b37 100644 --- a/tests/unit/jwt/test_access_token.py +++ b/tests/unit/jwt/test_access_token.py @@ -1,257 +1,253 @@ import time import unittest - from datetime import datetime -from nose.tools import assert_equal from twilio.jwt.access_token import AccessToken from twilio.jwt.access_token.grants import ( - IpMessagingGrant, SyncGrant, VoiceGrant, VideoGrant, - ConversationsGrant, TaskRouterGrant, - ChatGrant + ChatGrant, + PlaybackGrant, ) -ACCOUNT_SID = 'AC123' -SIGNING_KEY_SID = 'SK123' +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 + 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) + 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) + assert obj1 > obj2, "%r is not greater than or equal to %r" % (obj1, obj2) class AccessTokenTest(unittest.TestCase): def _validate_claims(self, payload): - assert_equal(SIGNING_KEY_SID, payload['iss']) - assert_equal(ACCOUNT_SID, payload['sub']) + assert SIGNING_KEY_SID == payload["iss"] + assert ACCOUNT_SID == payload["sub"] - assert_is_not_none(payload['exp']) - assert_is_not_none(payload['jti']) - assert_is_not_none(payload['grants']) + assert payload["exp"] is not None + assert payload["jti"] is not None + assert payload["grants"] is not None - assert_greater_equal(payload['exp'], int(time.time())) + assert payload["exp"] >= int(time.time()) - assert_in(payload['iss'], payload['jti']) + assert payload["iss"] in payload["jti"] def test_empty_grants(self): - scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret') + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret") token = scat.to_jwt() - assert_is_not_none(token) - decoded_token = AccessToken.from_jwt(token, 'secret') + assert token is not None + decoded_token = AccessToken.from_jwt(token, "secret") self._validate_claims(decoded_token.payload) - assert_equal({}, decoded_token.payload['grants']) + 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) + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret", nbf=now) token = scat.to_jwt() - assert_is_not_none(token) - decoded_token = AccessToken.from_jwt(token, 'secret') + assert token is not None + decoded_token = AccessToken.from_jwt(token, "secret") self._validate_claims(decoded_token.payload) - assert_equal(now, decoded_token.nbf) + assert now == decoded_token.nbf def test_headers(self): - scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret') + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret") token = scat.to_jwt() - assert_is_not_none(token) - decoded_token = AccessToken.from_jwt(token, 'secret') - self.assertEqual(decoded_token.headers['cty'], 'twilio-fpa;v=1') + 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') + scat = AccessToken( + ACCOUNT_SID, SIGNING_KEY_SID, "secret", identity="test@twilio.com" + ) token = scat.to_jwt() - assert_is_not_none(token) - decoded_token = AccessToken.from_jwt(token, 'secret') + assert token is not None + decoded_token = AccessToken.from_jwt(token, "secret") self._validate_claims(decoded_token.payload) - assert_equal({ - 'identity': 'test@twilio.com' - }, decoded_token.payload['grants']) + 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(ConversationsGrant(configuration_profile_sid='CP123')) + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret") + scat.add_grant(VoiceGrant(outgoing_application_sid="CP123")) token = scat.to_jwt() - assert_is_not_none(token) - decoded_token = AccessToken.from_jwt(token, 'secret') + assert token is not None + decoded_token = AccessToken.from_jwt(token, "secret") self._validate_claims(decoded_token.payload) - assert_equal(1, len(decoded_token.payload['grants'])) - assert_equal({ - 'configuration_profile_sid': 'CP123' - }, decoded_token.payload['grants']['rtc']) + 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')) + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret") + scat.add_grant(VideoGrant(room="RM123")) token = scat.to_jwt() - assert_is_not_none(token) - decoded_token = AccessToken.from_jwt(token, 'secret') + assert token is not None + decoded_token = AccessToken.from_jwt(token, "secret") self._validate_claims(decoded_token.payload) - assert_equal(1, len(decoded_token.payload['grants'])) - assert_equal({ - 'room': 'RM123' - }, decoded_token.payload['grants']['video']) - - def test_ip_messaging_grant(self): - scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret') - scat.add_grant(IpMessagingGrant(service_sid='IS123', push_credential_sid='CR123')) - - token = scat.to_jwt() - assert_is_not_none(token) - decoded_token = AccessToken.from_jwt(token, 'secret') - self._validate_claims(decoded_token.payload) - assert_equal(1, len(decoded_token.payload['grants'])) - assert_equal({ - 'service_sid': 'IS123', - 'push_credential_sid': 'CR123' - }, decoded_token.payload['grants']['ip_messaging']) + 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')) + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret") + scat.add_grant(ChatGrant(service_sid="IS123", push_credential_sid="CR123")) token = scat.to_jwt() - assert_is_not_none(token) - decoded_token = AccessToken.from_jwt(token, 'secret') + assert token is not None + decoded_token = AccessToken.from_jwt(token, "secret") self._validate_claims(decoded_token.payload) - assert_equal(1, len(decoded_token.payload['grants'])) - assert_equal({ - 'service_sid': 'IS123', - 'push_credential_sid': 'CR123' - }, decoded_token.payload['grants']['chat']) + 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 = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret") scat.identity = "bender" - scat.add_grant(SyncGrant(service_sid='IS123', endpoint_id='blahblahendpoint')) + scat.add_grant(SyncGrant(service_sid="IS123", endpoint_id="blahblahendpoint")) token = scat.to_jwt() - assert_is_not_none(token) - decoded_token = AccessToken.from_jwt(token, 'secret') + assert token is not None + decoded_token = AccessToken.from_jwt(token, "secret") self._validate_claims(decoded_token.payload) - assert_equal(2, len(decoded_token.payload['grants'])) - assert_equal("bender", decoded_token.payload['grants']['identity']) - assert_equal({ - 'service_sid': 'IS123', - 'endpoint_id': 'blahblahendpoint' - }, decoded_token.payload['grants']['data_sync']) + 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 = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret") scat.add_grant(VideoGrant()) - scat.add_grant(IpMessagingGrant()) + scat.add_grant(ChatGrant()) token = scat.to_jwt() - assert_is_not_none(token) - decoded_token = AccessToken.from_jwt(token, 'secret') + assert token is not None + decoded_token = AccessToken.from_jwt(token, "secret") self._validate_claims(decoded_token.payload) - assert_equal(2, len(decoded_token.payload['grants'])) - assert_equal({}, decoded_token.payload['grants']['video']) - assert_equal({}, decoded_token.payload['grants']['ip_messaging']) + 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' - } + outgoing_application_sid="AP123", outgoing_application_params={"foo": "bar"} ) - scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret') + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret") scat.add_grant(grant) token = scat.to_jwt() - assert_is_not_none(token) - decoded_token = AccessToken.from_jwt(token, 'secret') + assert token is not None + decoded_token = AccessToken.from_jwt(token, "secret") self._validate_claims(decoded_token.payload) - assert_equal(1, len(decoded_token.payload['grants'])) - assert_equal({ - 'outgoing': { - 'application_sid': 'AP123', - 'params': { - 'foo': 'bar' - } - } - }, decoded_token.payload['grants']['voice']) + 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 - ) + grant = VoiceGrant(incoming_allow=True) - scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret') + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret") scat.add_grant(grant) token = scat.to_jwt() - assert_is_not_none(token) - decoded_token = AccessToken.from_jwt(token, 'secret') + assert token is not None + decoded_token = AccessToken.from_jwt(token, "secret") self._validate_claims(decoded_token.payload) - assert_equal(1, len(decoded_token.payload['grants'])) - assert_equal({ - 'incoming': { - 'allow': True - } - }, decoded_token.payload['grants']['voice']) + 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' + workspace_sid="WS123", worker_sid="WK123", role="worker" ) - scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret') + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret") scat.add_grant(grant) token = scat.to_jwt() - assert_is_not_none(token) - decoded_token = AccessToken.from_jwt(token, 'secret') + assert token is not None + decoded_token = AccessToken.from_jwt(token, "secret") self._validate_claims(decoded_token.payload) - assert_equal(1, len(decoded_token.payload['grants'])) - assert_equal({ - 'workspace_sid': 'WS123', - 'worker_sid': 'WK123', - 'role': 'worker' - }, decoded_token.payload['grants']['task_router']) + 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(), - IpMessagingGrant() - ] - scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret', grants=grants) + grants = [VideoGrant(), ChatGrant()] + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret", grants=grants) token = scat.to_jwt() - assert_is_not_none(token) + assert token is not None - decoded_token = AccessToken.from_jwt(token, 'secret') + decoded_token = AccessToken.from_jwt(token, "secret") self._validate_claims(decoded_token.payload) - assert_equal(2, len(decoded_token.payload['grants'])) - assert_equal({}, decoded_token.payload['grants']['video']) - assert_equal({}, decoded_token.payload['grants']['ip_messaging']) + 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) + 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 = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret") scat.add_grant(VideoGrant()) - self.assertRaises(ValueError, scat.add_grant, 'GrantRootAccess') + self.assertRaises(ValueError, scat.add_grant, "GrantRootAccess") diff --git a/tests/unit/jwt/test_client.py b/tests/unit/jwt/test_client.py index 5cbd937f45..3fa90de9f8 100644 --- a/tests/unit/jwt/test_client.py +++ b/tests/unit/jwt/test_client.py @@ -1,33 +1,30 @@ -import unittest - import time -from nose.tools import assert_true, assert_equal +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""" - return assert_true(foo in bar, msg=(msg or "%s not found in %s" % (foo, bar))) + 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_equal(len(token._generate_payload()), 1) - assert_equal(token._generate_payload()["scope"], '') + 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_equal(len(token._generate_payload()), 1) - assert_equal(token._generate_payload()['scope'], eurl) + assert len(token._generate_payload()) == 1 + assert token._generate_payload()["scope"] == eurl def test_outbound_permissions(self): token = ClientCapabilityToken("AC123", "XXXXX") @@ -35,29 +32,31 @@ def test_outbound_permissions(self): eurl = "scope:client:outgoing?appSid=AP123" - assert_equal(len(token._generate_payload()), 1) - self.assertIn(eurl, token._generate_payload()['scope']) + 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_equal(token.payload["scope"], eurl) + 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_equal(token.payload["scope"], event_uri) + 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_equal(token.payload["scope"], event_uri) + 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") @@ -65,7 +64,9 @@ def test_decode(self): token.allow_client_incoming("andy") token.allow_event_stream() - outgoing_uri = "scope:client:outgoing?appParams=foobar%3D3&appSid=AP123&clientName=andy" + 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" @@ -81,34 +82,38 @@ def test_encode_full_payload(self): token.allow_event_stream(foobar="hey") token.allow_client_incoming("andy") - event_uri = "scope:stream:subscribe?params=foobar%3Dhey&path=%2F2010-04-01%2FEvents" + 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()) + 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' - }) + 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()) + 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()) + 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()) + 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 index 5e0ddb8995..56d70d8152 100644 --- a/tests/unit/jwt/test_client_validation.py +++ b/tests/unit/jwt/test_client_validation.py @@ -1,5 +1,5 @@ -import unittest import time +import unittest from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import rsa @@ -7,280 +7,315 @@ Encoding, PublicFormat, PrivateFormat, - NoEncryption + NoEncryption, ) from twilio.http.validation_client import ValidationPayload -from twilio.jwt import Jwt 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' + 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 = "\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) + 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']) + 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' + 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 = "\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) + 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']) + 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' + 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 = "\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) + 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']) + 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='' + 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 = "\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) + 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']) + 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' + 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 = "\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) + 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']) + 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'], + method="GET", + path="https://api.twilio.com/", + query_string="q1=v1", + signed_headers=["headerb", "headera"], all_headers={}, - body='me=letop&you=leworst' + 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 = "\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) + 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']) + 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' + 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' + expected_hash = ( + "4dc9b67bed579647914587b0e22a1c65c1641d8674797cd82de65e766cce5f80" + ) - jwt = ClientValidationJwt('AC123', 'SK123', 'CR123', 'secret', vp) + 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']) + 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' + method="POST", + path="/Messages", + query_string="", + signed_headers=["authorization", "host"], + all_headers={"authorization": "foobar", "host": "api.twilio.com"}, + body="testbody", ) - expected_hash = 'bd792c967c20d546c738b94068f5f72758a10d26c12979677501e1eefe58c65a' + expected_hash = ( + "bd792c967c20d546c738b94068f5f72758a10d26c12979677501e1eefe58c65a" + ) - jwt = ClientValidationJwt('AC123', 'SK123', 'CR123', 'secret', vp) + 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']) + 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' + 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, ) - expected_hash = '4dc9b67bed579647914587b0e22a1c65c1641d8674797cd82de65e766cce5f80' - - jwt = ClientValidationJwt('AC123', 'SK123', 'CR123', 'secret', vp) - - self.assertDictContainsSubset({ - 'hrh': 'authorization;host', - 'rqh': expected_hash, - 'iss': 'SK123', - 'sub': 'AC123', - }, jwt.payload) - 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' + 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" ) - expected_hash = '4dc9b67bed579647914587b0e22a1c65c1641d8674797cd82de65e766cce5f80' private_key = rsa.generate_private_key( - public_exponent=65537, - key_size=2048, - backend=default_backend() + 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() ) - 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 = Jwt.from_jwt(jwt.to_jwt(), public_key) - - self.assertDictContainsSubset({ - 'hrh': 'authorization;host', - 'rqh': expected_hash, - 'iss': 'SK123', - 'sub': 'AC123', - }, decoded.payload) - 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) - + 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 index 053bb610bf..2f5aba62d7 100644 --- a/tests/unit/jwt/test_jwt.py +++ b/tests/unit/jwt/test_jwt.py @@ -1,8 +1,7 @@ -import unittest -import jwt as jwt_lib import time as real_time +import unittest -from nose.tools import assert_true +import jwt as jwt_lib from mock import patch from twilio.jwt import Jwt, JwtDecodeError @@ -10,16 +9,29 @@ class DummyJwt(Jwt): """Jwt implementation that allows setting arbitrary payload and headers for testing.""" - def __init__(self, secret_key, issuer, subject=None, algorithm='HS256', nbf=Jwt.GENERATE, - ttl=3600, valid_until=None, headers=None, payload=None): + + 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, + algorithm=algorithm or self.ALGORITHM, nbf=nbf, ttl=ttl, - valid_until=valid_until + valid_until=valid_until, ) self._payload = payload or {} self._headers = headers or {} @@ -34,7 +46,7 @@ def _generate_headers(self): class JwtTest(unittest.TestCase): def assertIn(self, foo, bar, msg=None): """backport for 2.6""" - return assert_true(foo in bar, msg=(msg or "%s not found in %s" % (foo, bar))) + assert foo in bar, msg or "%s not found in %s" % (foo, bar) def now(self): return int(real_time.time()) @@ -43,237 +55,248 @@ 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, verify=False) + 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') + @patch("time.time") def test_basic_encode(self, time_mock): time_mock.return_value = 0.0 - jwt = DummyJwt('secret_key', 'issuer', headers={}, payload={}) + 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}, + jwt.to_jwt(), + "secret_key", + expected_headers={"typ": "JWT", "alg": "HS256"}, + expected_payload={"iss": "issuer", "exp": 3600, "nbf": 0}, ) - @patch('time.time') + @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={}) + 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'}, + jwt.to_jwt(), + "secret_key", + expected_headers={"typ": "JWT", "alg": "HS256"}, + expected_payload={"iss": "issuer", "exp": 3600, "nbf": 0, "sub": "subject"}, ) - @patch('time.time') + @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) + 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'}, + jwt.to_jwt(), + "secret_key", + expected_headers={"typ": "JWT", "alg": "HS256"}, + expected_payload={"iss": "issuer", "exp": 3600, "sub": "subject"}, ) - @patch('time.time') + @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={}) + 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}, + jwt.to_jwt(), + "secret_key", + expected_headers={"typ": "JWT", "alg": "HS256"}, + expected_payload={"iss": "issuer", "exp": 10, "nbf": 0}, ) - @patch('time.time') + @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={}) + 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}, + jwt.to_jwt(), + "secret_key", + expected_headers={"typ": "JWT", "alg": "HS256"}, + expected_payload={"iss": "issuer", "exp": 60, "nbf": 50}, ) - @patch('time.time') + @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={}) + 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}, + "secret_key", + expected_headers={"typ": "JWT", "alg": "HS256"}, + expected_payload={"iss": "issuer", "exp": 20, "nbf": 0}, ) - @patch('time.time') + @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}, + jwt = DummyJwt( + "secret_key", "issuer", ttl=10, valid_until=70, headers={}, payload={} ) - @patch('time.time') - def test_encode_custom_algorithm(self, time_mock): - time_mock.return_value = 0.0 - - jwt = DummyJwt('secret_key', 'issuer', algorithm='HS512', headers={}, payload={}) - self.assertJwtsEqual( - jwt.to_jwt(), 'secret_key', - expected_headers={'typ': 'JWT', 'alg': 'HS512'}, - expected_payload={'iss': 'issuer', 'exp': 3600, 'nbf': 0}, + 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_override_algorithm(self, time_mock): + @patch("time.time") + def test_encode_custom_nbf(self, time_mock): time_mock.return_value = 0.0 - jwt = DummyJwt('secret_key', 'issuer', algorithm='HS256', headers={}, payload={}) + jwt = DummyJwt("secret_key", "issuer", ttl=10, nbf=5, headers={}, payload={}) self.assertJwtsEqual( - jwt.to_jwt(algorithm='HS512'), - 'secret_key', - expected_headers={'typ': 'JWT', 'alg': 'HS512'}, - expected_payload={'iss': 'issuer', 'exp': 3600, 'nbf': 0}, + jwt.to_jwt(), + "secret_key", + expected_headers={"typ": "JWT", "alg": "HS256"}, + expected_payload={"iss": "issuer", "exp": 10, "nbf": 5}, ) - @patch('time.time') + @patch("time.time") def test_encode_with_headers(self, time_mock): time_mock.return_value = 0.0 - jwt = DummyJwt('secret_key', 'issuer', algorithm='HS256', headers={'sooper': 'secret'}, - payload={}) + 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}, + jwt.to_jwt(), + "secret_key", + expected_headers={"typ": "JWT", "alg": "HS256", "sooper": "secret"}, + expected_payload={"iss": "issuer", "exp": 3600, "nbf": 0}, ) - @patch('time.time') + @patch("time.time") def test_encode_with_payload(self, time_mock): time_mock.return_value = 0.0 - jwt = DummyJwt('secret_key', 'issuer', algorithm='HS256', payload={'root': 'true'}) + 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'}, + jwt.to_jwt(), + "secret_key", + expected_headers={"typ": "JWT", "alg": "HS256"}, + expected_payload={"iss": "issuer", "exp": 3600, "nbf": 0, "root": "true"}, ) - @patch('time.time') + @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'}) + 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'}, + 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_invalid_crypto_alg_fails(self): - jwt = DummyJwt('secret_key', 'issuer', algorithm='PlzDontTouchAlgorithm') - self.assertRaises(NotImplementedError, jwt.to_jwt) - def test_encode_no_key_fails(self): - jwt = DummyJwt(None, 'issuer') + 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') + 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.assertDictContainsSubset({ - 'iss': 'issuer', - 'sub': 'hey', - 'sick': 'sick', - }, decoded_jwt.payload) + 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') + 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().decode('utf-8') - example_jwt = 'ABC' + example_jwt[3:] - example_jwt = example_jwt.encode('utf-8') + 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') + 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()) + 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') + 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') + 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' + {"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') + 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') + 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'}) + 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.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 index 8669eb4895..f2333ef327 100644 --- a/tests/unit/jwt/test_task_router.py +++ b/tests/unit/jwt/test_task_router.py @@ -10,14 +10,14 @@ 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) + 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() @@ -61,32 +61,41 @@ def test_default(self): decoded = TaskQueueCapabilityToken.from_jwt(token, self.auth_token) self.assertNotEqual(None, decoded) - policies = decoded.payload['policies'] + 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']) + 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']) + 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']) + 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() @@ -97,17 +106,20 @@ def test_allow_fetch_subresources(self): decoded = TaskQueueCapabilityToken.from_jwt(token, self.auth_token) self.assertNotEqual(None, decoded) - policies = decoded.payload['policies'] + 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']) + 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() @@ -118,22 +130,29 @@ def test_allow_updates_subresources(self): decoded = TaskQueueCapabilityToken.from_jwt(token, self.auth_token) self.assertNotEqual(None, decoded) - policies = decoded.payload['policies'] + 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']) + 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) + 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) @@ -141,28 +160,33 @@ def test_pass_policy_in_constructor(self): decoded = TaskQueueCapabilityToken.from_jwt(token, self.auth_token) self.assertNotEqual(None, decoded) - policies = decoded.payload['policies'] + 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']) + 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']) + 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): + 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) @@ -170,18 +194,19 @@ def check_decoded(self, decoded, account_sid, workspace_sid, channel_id, channel 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) + 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) + 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() @@ -190,8 +215,13 @@ def test_generate_token(self): 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) + 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() @@ -218,23 +248,38 @@ def test_defaults(self): 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 + 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'] + 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]) + ("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 @@ -248,21 +293,20 @@ def test_allow_activity_updates(self): decoded = WorkerCapabilityToken.from_jwt(token, self.auth_token) self.assertNotEqual(None, decoded) - policies = decoded.payload['policies'] + 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.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']) + 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 @@ -274,22 +318,30 @@ def test_allow_reservation_updates(self): decoded = WorkerCapabilityToken.from_jwt(token, self.auth_token) self.assertNotEqual(None, decoded) - policies = decoded.payload['policies'] + 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) + 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) + 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) + 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) @@ -297,27 +349,33 @@ def test_pass_policies_in_constructor(self): decoded = WorkerCapabilityToken.from_jwt(token, self.auth_token) self.assertNotEqual(None, decoded) - policies = decoded.payload['policies'] + 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) + 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) + 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']) + 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): + 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) @@ -325,17 +383,18 @@ def check_decoded(self, decoded, account_sid, workspace_sid, channel_id, channel 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) + 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) + self.capability = WorkspaceCapabilityToken( + self.account_sid, self.auth_token, self.workspace_sid + ) def test_generate_token(self): token = self.capability.to_jwt() @@ -344,7 +403,9 @@ def test_generate_token(self): 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) + 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() @@ -373,13 +434,21 @@ def test_default(self): decoded = WorkspaceCapabilityToken.from_jwt(token, self.auth_token) self.assertNotEqual(None, decoded) - policies = decoded.payload['policies'] + 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]) + ( + "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 @@ -392,12 +461,14 @@ def test_allow_fetch_subresources(self): decoded = WorkspaceCapabilityToken.from_jwt(token, self.auth_token) self.assertNotEqual(None, decoded) - policies = decoded.payload['policies'] + 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) + self.check_policy( + "GET", "https://taskrouter.twilio.com/v1/Workspaces/WS456/**", policy + ) def test_allow_updates_subresources(self): self.capability.allow_update_subresources() @@ -408,17 +479,22 @@ def test_allow_updates_subresources(self): decoded = WorkspaceCapabilityToken.from_jwt(token, self.auth_token) self.assertNotEqual(None, decoded) - policies = decoded.payload['policies'] + 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) + 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) + 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) @@ -426,12 +502,14 @@ def test_pass_policy_in_constructor(self): decoded = WorkspaceCapabilityToken.from_jwt(token, self.auth_token) self.assertNotEqual(None, decoded) - policies = decoded.payload['policies'] + 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) + self.check_policy( + "POST", "https://taskrouter.twilio.com/v1/Workspaces/WS456/**", policy + ) if __name__ == "__main__": diff --git a/tests/unit/rest/test_client.py b/tests/unit/rest/test_client.py index 5600505718..9623dc52ad 100644 --- a/tests/unit/rest/test_client.py +++ b/tests/unit/rest/test_client.py @@ -1,46 +1,142 @@ import unittest -from twilio.rest import ( - TwilioClient, - TwilioRestClient, - TwilioIpMessagingClient, - TwilioLookupsClient, - TwilioMonitorClient, - TwilioPricingClient, - TwilioTaskRouterClient, - TwilioTrunkingClient, -) -from twilio.base.obsolete import ObsoleteException - - -class TestDummyClients(unittest.TestCase): - def test_obsolete_exception_twilioclient(self): - self.assertRaises(ObsoleteException, TwilioClient, - "Expected raised ObsoleteException") - - def test_obsolete_exception_twiliorestclient(self): - self.assertRaises(ObsoleteException, TwilioRestClient, - "Expected raised ObsoleteException") - - def test_obsolete_exception_twilioipmessagingclient(self): - self.assertRaises(ObsoleteException, TwilioIpMessagingClient, - "Expected raised ObsoleteException") - - def test_obsolete_exception_twiliolookupsclient(self): - self.assertRaises(ObsoleteException, TwilioLookupsClient, - "Expected raised ObsoleteException") - - def test_obsolete_exception_twiliomonitorclient(self): - self.assertRaises(ObsoleteException, TwilioMonitorClient, - "Expected raised ObsoleteException") - - def test_obsolete_exception_twiliopricingclient(self): - self.assertRaises(ObsoleteException, TwilioPricingClient, - "Expected raised ObsoleteException") - - def test_obsolete_exception_twiliotaskrouterclient(self): - self.assertRaises(ObsoleteException, TwilioTaskRouterClient, - "Expected raised ObsoleteException") - - def test_obsolete_exception_twiliotrunkingclient(self): - self.assertRaises(ObsoleteException, TwilioTrunkingClient, - "Expected raised ObsoleteException") +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 index 237ab5ba01..2159d4c910 100644 --- a/tests/unit/test_request_validator.py +++ b/tests/unit/test_request_validator.py @@ -1,67 +1,95 @@ # -*- coding: utf-8 -*- import unittest -from nose.tools import assert_equal, assert_true -from six import b, u +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): - token = "1c892n40nd03kdnc0112slzkl3091j20" + if not settings.configured: + settings.configure() + + token = "12345" self.validator = RequestValidator(token) - self.uri = "http://www.postbin.org/1ed898x" + self.uri = "https://mycompany.com/myapp.php?foo=1&bar=2" self.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", + "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_bytecode(self): - expected = b("fF+xx6dTinOaCdZ0aIeNkHr/ZAA=") - signature = self.validator.compute_signature(self.uri, - self.params, - utf=False) - assert_equal(signature, expected) + 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_unicode(self): - expected = u("fF+xx6dTinOaCdZ0aIeNkHr/ZAA=") - signature = self.validator.compute_signature(self.uri, - self.params, - utf=True) - assert_equal(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): - expected = "fF+xx6dTinOaCdZ0aIeNkHr/ZAA=" - assert_true(self.validator.validate(self.uri, self.params, expected)) + assert self.validator.validate(self.uri, self.params, self.expected) def test_validation_removes_port_on_https(self): - self.uri = "https://www.postbin.org:1234/1ed898x" - expected = "Y7MeICc5ECftd1G11Fc8qoxAn0A=" - assert_true(self.validator.validate(self.uri, self.params, expected)) + 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 index 2681336661..cb78511a51 100644 --- a/tests/unit/twiml/__init__.py +++ b/tests/unit/twiml/__init__.py @@ -1,58 +1,60 @@ import unittest -from nose.tools import raises -from six import text_type +from pytest import raises -from twilio.twiml import ( - format_language, - lower_camel, - TwiMLException, - TwiML -) +from twilio.twiml import format_language, lower_camel, TwiMLException, TwiML class TwilioTest(unittest.TestCase): def strip(self, xml): - return text_type(xml) + return str(xml) - @raises(TwiMLException) def test_append_fail(self): - t = TwiML() - t.append('foobar') + 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' + 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)) + language = "EN_us" + self.assertEqual("en-US", format_language(language)) - @raises(TwiMLException) def test_format_language_fail(self): - format_language('this is invalid') + with raises(TwiMLException): + format_language("this is invalid") def test_lower_camel_empty_string(self): - self.assertEqual('', lower_camel('')) + 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')) + self.assertEqual("foo", lower_camel("foo")) def test_lower_camel_double_word(self): - self.assertEqual('fooBar', lower_camel('foo_bar')) + self.assertEqual("fooBar", lower_camel("foo_bar")) def test_lower_camel_multi_word(self): - self.assertEqual('fooBarBaz', lower_camel('foo_bar_baz')) + 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')) + self.assertEqual("fooBarBaz", lower_camel("foO_Bar_baz")) def test_lower_camel_camel_cased(self): - self.assertEqual('fooBar', lower_camel('fooBar')) + self.assertEqual("fooBar", lower_camel("fooBar")) + + def test_utf8_encoding(self): + t = TwiML() + t.value = "An utf-8 character: ñ" + self.assertEqual( + t.to_xml(), + 'An utf-8 character: ñ', + ) diff --git a/tests/unit/twiml/test_messaging_response.py b/tests/unit/twiml/test_messaging_response.py index bc9d9efb09..286b5ba770 100644 --- a/tests/unit/twiml/test_messaging_response.py +++ b/tests/unit/twiml/test_messaging_response.py @@ -1,90 +1,128 @@ -from nose.tools import assert_equal 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_equal( - self.strip(r), - '' - ) + assert self.strip(r) == '' def test_response(self): r = MessagingResponse() - r.message('Hello') - r.redirect(url='example.com') + r.message("Hello") + r.redirect(url="example.com") - assert_equal( - self.strip(r), - 'Helloexample.com' + assert ( + self.strip(r) + == 'Helloexample.com' ) def test_response_chain(self): with MessagingResponse() as r: - r.message('Hello') - r.redirect(url='example.com') + r.message("Hello") + r.redirect(url="example.com") - assert_equal( - self.strip(r), - 'Helloexample.com' + assert ( + self.strip(r) + == 'Helloexample.com' ) def test_nested_verbs(self): with MessagingResponse() as r: - with r.message('Hello') as m: - m.media('example.com') + with r.message("Hello") as m: + m.media("example.com") - assert_equal( - self.strip(r), - 'Helloexample.com' + assert ( + self.strip(r) + == 'Helloexample.com' ) + 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) + == 'Hello' + ) + + def test_mixed(self): + r = MessagingResponse() + + r.append("before") + r.add_child("Child").append("content") + r.append("after") + + assert ( + self.strip(r) + == 'beforecontentafter' + ) -class TestMessage(TwilioTest): +class TestMessage(TwilioTest): def test_body(self): r = MessagingResponse() - r.message('Hello') + r.message("Hello") - assert_equal( - self.strip(r), - 'Hello' + assert ( + self.strip(r) + == 'Hello' ) def test_nested_body(self): - b = Body('Hello World') + b = Body("Hello World") r = MessagingResponse() r.append(b) - assert_equal( - self.strip(r), - 'Hello World' + assert ( + self.strip(r) + == 'Hello World' ) def test_nested_body_media(self): - b = Body('Hello World') - m = Media('hey.jpg') + b = Body("Hello World") + m = Media("hey.jpg") r = MessagingResponse() r.append(b) r.append(m) - assert_equal( - self.strip(r), - 'Hello Worldhey.jpg' + assert ( + self.strip(r) + == 'Hello Worldhey.jpg' ) class TestRedirect(TwilioTest): def test_redirect(self): r = MessagingResponse() - r.redirect(url='example.com') + r.redirect(url="example.com") + + assert ( + self.strip(r) + == 'example.com' + ) + + +class TestText(TwilioTest): + def test_text(self): + r = MessagingResponse() + r.append("No tags!") + + assert ( + self.strip(r) + == 'No tags!' + ) + + def text_mixed(self): + r = MessagingResponse() + r.append("before") + r.append(Body("Content")) + r.append("after") - assert_equal( - self.strip(r), - 'example.com' + assert ( + self.strip(r) + == 'beforeContentafter' ) diff --git a/tests/unit/twiml/test_voice_response.py b/tests/unit/twiml/test_voice_response.py index b5ed2213b3..df10fc7d62 100644 --- a/tests/unit/twiml/test_voice_response.py +++ b/tests/unit/twiml/test_voice_response.py @@ -1,604 +1,629 @@ # -*- coding: utf-8 -*- -from nose.tools import assert_equal -from six import u 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_equal( - self.strip(r), - '' - ) + assert self.strip(r) == '' def test_response(self): r = VoiceResponse() r.hangup() r.leave() - r.sms( - 'twilio sms', - to='+11234567890', - from_='+10987654321' - ) + r.sms("twilio sms", to="+11234567890", from_="+10987654321") - assert_equal( - self.strip(r), - 'twilio sms' + assert ( + self.strip(r) + == '' + 'twilio sms' ) def test_response_chain(self): with VoiceResponse() as r: r.hangup() r.leave() - r.sms( - 'twilio sms', - to='+11234567890', - from_='+10987654321' - ) + r.sms("twilio sms", to="+11234567890", from_="+10987654321") - assert_equal( - self.strip(r), - 'twilio sms' + assert ( + self.strip(r) + == '' + 'twilio sms' ) def test_nested_verbs(self): with VoiceResponse() as r: with r.gather() as g: - g.say('Hello', voice='man') + g.say("Hello", voice="man") - assert_equal( - self.strip(r), - 'Hello' + assert ( + self.strip(r) + == 'Hello' ) class TestSay(TwilioTest): - def test_empty_say(self): - """ should be a say with no text """ + """should be a say with no text""" r = VoiceResponse() - r.say('') + r.say("") - assert_equal( - self.strip(r), - '' + assert ( + self.strip(r) + == '' ) def test_say_hello_world(self): - """ should say hello world """ + """should say hello world""" r = VoiceResponse() - r.say('Hello World') + r.say("Hello World") - assert_equal( - self.strip(r), - 'Hello World' + assert ( + self.strip(r) + == 'Hello World' ) def test_say_french(self): - """ should say hello monkey """ + """should say hello monkey""" r = VoiceResponse() - r.say(u('n\xe9cessaire et d\'autres')) + r.say("n\xe9cessaire et d'autres") - assert_equal( - self.strip(r), - 'nécessaire et d\'autres' + assert ( + self.strip(r) + == 'nécessaire et d\'autres' ) def test_say_loop(self): - """ should say hello monkey and loop 3 times """ + """should say hello monkey and loop 3 times""" r = VoiceResponse() - r.say('Hello Monkey', loop=3) + r.say("Hello Monkey", loop=3) - assert_equal( - self.strip(r), - 'Hello Monkey' + assert ( + self.strip(r) + == 'Hello Monkey' ) def test_say_loop_gb(self): - """ should say have a woman say hello monkey and loop 3 times """ + """should say have a woman say hello monkey and loop 3 times""" r = VoiceResponse() - r.say('Hello Monkey', language='en-gb') + r.say("Hello Monkey", language="en-gb") - assert_equal( - self.strip(r), - 'Hello Monkey' + assert ( + self.strip(r) + == 'Hello Monkey' ) def test_say_loop_woman(self): - """ should say have a woman say hello monkey and loop 3 times """ + """should say have a woman say hello monkey and loop 3 times""" r = VoiceResponse() - r.say('Hello Monkey', loop=3, voice='woman') + r.say("Hello Monkey", loop=3, voice="woman") - assert_equal( - self.strip(r), - 'Hello Monkey' + assert ( + self.strip(r) + == 'Hello Monkey' ) def test_say_all(self): - """ convenience method: should say have a woman say hello monkey and loop 3 times and be in french """ + """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') + r.say("Hello Monkey", loop=3, voice="man", language="fr") - assert_equal( - self.strip(r), - 'Hello Monkey' + assert ( + self.strip(r) + == '' + "Hello Monkey" ) class TestPlay(TwilioTest): - def test_empty_play(self): - """ should play hello monkey """ + """should play hello monkey""" r = VoiceResponse() r.play() - assert_equal( - self.strip(r), - '' + assert ( + self.strip(r) + == '' ) def test_play_hello(self): - """ should play hello monkey """ + """should play hello monkey""" r = VoiceResponse() - r.play(url='http://hellomonkey.mp3') + r.play(url="http://hellomonkey.mp3") - assert_equal( - self.strip(r), - 'http://hellomonkey.mp3' + assert ( + self.strip(r) + == 'http://hellomonkey.mp3' ) def test_play_hello_loop(self): - """ should play hello monkey loop """ + """should play hello monkey loop""" r = VoiceResponse() - r.play(url='http://hellomonkey.mp3', loop=3) + r.play(url="http://hellomonkey.mp3", loop=3) - assert_equal( - self.strip(r), - 'http://hellomonkey.mp3' + assert ( + self.strip(r) + == 'http://hellomonkey.mp3' ) def test_play_digits(self): - """ should play digits """ + """should play digits""" r = VoiceResponse() - r.play(digits='w123') + r.play(digits="w123") - assert_equal( - self.strip(r), - '' + assert ( + self.strip(r) + == '' ) class TestRecord(TwilioTest): - def test_record_empty(self): - """ should record """ + """should record""" r = VoiceResponse() r.record() - assert_equal( - self.strip(r), - '' + assert ( + self.strip(r) + == '' ) def test_record_action_method(self): - """ should record with an action and a get method """ + """should record with an action and a get method""" r = VoiceResponse() - r.record(action='example.com', method='GET') + r.record(action="example.com", method="GET") - assert_equal( - self.strip(r), - '' + assert ( + self.strip(r) + == '' ) def test_record_max_length_finish_timeout(self): - """ should record with an maxLength, finishOnKey, and timeout """ + """should record with an maxLength, finishOnKey, and timeout""" r = VoiceResponse() - r.record(timeout=4, finish_on_key='#', max_length=30) + r.record(timeout=4, finish_on_key="#", max_length=30) - assert_equal( - self.strip(r), - '' + assert ( + self.strip(r) + == '' ) def test_record_transcribe(self): - """ should record with a transcribe and transcribeCallback """ + """should record with a transcribe and transcribeCallback""" r = VoiceResponse() - r.record(transcribe_callback='example.com') + r.record(transcribe_callback="example.com") - assert_equal( - self.strip(r), - '' + assert ( + self.strip(r) + == '' ) class TestRedirect(TwilioTest): - def test_redirect_empty(self): r = VoiceResponse() - r.redirect('') + r.redirect("") - assert_equal( - self.strip(r), - '' + assert ( + self.strip(r) + == '' ) def test_redirect_method(self): r = VoiceResponse() - r.redirect('example.com', method='POST') + r.redirect("example.com", method="POST") - assert_equal( - self.strip(r), - 'example.com' + assert ( + self.strip(r) + == 'example.com' ) def test_redirect_method_params(self): r = VoiceResponse() - r.redirect('example.com?id=34&action=hey', method='POST') + r.redirect("example.com?id=34&action=hey", method="POST") - assert_equal( - self.strip(r), - 'example.com?id=34&action=hey' + assert ( + self.strip(r) == '' + 'example.com?id=34&action=hey' ) class TestHangup(TwilioTest): - def test_hangup(self): - """ convenience: should Hangup to a url via POST """ + """convenience: should Hangup to a url via POST""" r = VoiceResponse() r.hangup() - assert_equal( - self.strip(r), - '' + assert ( + self.strip(r) + == '' ) class TestLeave(TwilioTest): - def test_leave(self): - """ convenience: should Hangup to a url via POST """ + """convenience: should Hangup to a url via POST""" r = VoiceResponse() r.leave() - assert_equal( - self.strip(r), - '' + assert ( + self.strip(r) + == '' ) class TestReject(TwilioTest): - def test_reject(self): - """ should be a Reject with default reason """ + """should be a Reject with default reason""" r = VoiceResponse() r.reject() - assert_equal( - self.strip(r), - '' + assert ( + self.strip(r) + == '' ) class TestSms(TwilioTest): - def test_empty(self): - """ Test empty sms verb """ + """Test empty sms verb""" r = VoiceResponse() - r.sms('') + r.sms("") - assert_equal( - self.strip(r), - '' + assert ( + self.strip(r) + == '' ) def test_body(self): - """ Test hello world """ + """Test hello world""" r = VoiceResponse() - r.sms('Hello, World') + r.sms("Hello, World") - assert_equal( - self.strip(r), - 'Hello, World' + assert ( + self.strip(r) + == 'Hello, World' ) def test_to_from_action(self): - """ Test the to, from, and status callback """ + """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') + r.sms( + "Hello, World", + to=1231231234, + from_=3453453456, + status_callback="example.com?id=34&action=hey", + ) - assert_equal( - self.strip(r), - 'Hello, World' + assert ( + self.strip(r) == '' + '' + "Hello, World" ) def test_action_method(self): - """ Test the action and method parameters on Sms """ + """Test the action and method parameters on Sms""" r = VoiceResponse() - r.sms('Hello', method='POST', action='example.com?id=34&action=hey') + r.sms("Hello", method="POST", action="example.com?id=34&action=hey") - assert_equal( - self.strip(r), - 'Hello' + assert ( + self.strip(r) == '' + 'Hello' ) class TestConference(TwilioTest): - def test_conference(self): d = Dial() d.conference( - 'TestConferenceAttributes', + "TestConferenceAttributes", beep=False, - wait_url='', + wait_url="", start_conference_on_enter=True, - end_conference_on_exit=True + end_conference_on_exit=True, ) r = VoiceResponse() r.append(d) - assert_equal( - self.strip(r), - 'TestConferenceAttributes' + assert ( + self.strip(r) == '' + '' + "TestConferenceAttributes" ) def test_muted_conference(self): d = Dial() d.conference( - 'TestConferenceMutedAttribute', + "TestConferenceMutedAttribute", beep=False, muted=True, - wait_url='', + wait_url="", start_conference_on_enter=True, - end_conference_on_exit=True + end_conference_on_exit=True, ) r = VoiceResponse() r.append(d) - assert_equal( - self.strip(r), - 'TestConferenceMutedAttribute' + assert ( + self.strip(r) == '' + '' + "TestConferenceMutedAttribute" ) class TestQueue(TwilioTest): - def test_queue(self): d = Dial() - d.queue('TestQueueAttribute', url='', method='GET') + d.queue("TestQueueAttribute", url="", method="GET") r = VoiceResponse() r.append(d) - assert_equal( - self.strip(r), - 'TestQueueAttribute' + assert ( + self.strip(r) == '' + 'TestQueueAttribute' ) class TestEcho(TwilioTest): - def test_echo(self): r = VoiceResponse() r.echo() - assert_equal( - self.strip(r), - '' + assert ( + self.strip(r) + == '' ) class TestEnqueue(TwilioTest): - def test_enqueue(self): r = VoiceResponse() r.enqueue( - 'TestEnqueueAttribute', - action='act', - method='GET', - wait_url='wait', - wait_url_method='POST' + "TestEnqueueAttribute", + action="act", + method="GET", + wait_url="wait", + wait_url_method="POST", ) - assert_equal( - self.strip(r), - 'TestEnqueueAttribute' + assert ( + self.strip(r) == '' + 'TestEnqueueAttribute' + "" ) def test_task_string(self): - e = Enqueue(None, workflowSid='123123123') + e = Enqueue(None, workflowSid="123123123") e.task('{"account_sid": "AC123123123"}') r = VoiceResponse() r.append(e) - assert_equal( - self.strip(r), - '{"account_sid": "AC123123123"}' + assert ( + self.strip(r) + == '' + '{"account_sid": "AC123123123"}' ) def test_task_dict(self): - e = Enqueue(None, workflowSid='123123123') + e = Enqueue(None, workflowSid="123123123") e.task({"account_sid": "AC123123123"}) r = VoiceResponse() r.append(e) - assert_equal( - '{"account_sid": "AC123123123"}', + assert ( self.strip(r) + == '' + '{"account_sid": "AC123123123"}' ) class TestDial(TwilioTest): - def test_dial(self): - """ should redirect the call """ + """should redirect the call""" r = VoiceResponse() r.dial("1231231234") - assert_equal( - self.strip(r), - '1231231234' + assert ( + self.strip(r) + == '1231231234' ) def test_sim(self): d = Dial() - d.sim('123123123') + d.sim("123123123") r = VoiceResponse() r.append(d) - assert_equal( - self.strip(r), - '123123123' + assert ( + self.strip(r) + == '123123123' ) def test_sip(self): - """ should redirect the call """ + """should redirect the call""" d = Dial() - d.sip('foo@example.com') + d.sip("foo@example.com") r = VoiceResponse() r.append(d) - assert_equal( - self.strip(r), - 'foo@example.com' + assert ( + self.strip(r) + == 'foo@example.com' ) def test_sip_username_password(self): - """ should redirect the call """ + """should redirect the call""" d = Dial() - d.sip('foo@example.com', username='foo', password='bar') + d.sip("foo@example.com", username="foo", password="bar") r = VoiceResponse() r.append(d) - assert_equal( - self.strip(r), - 'foo@example.com' + assert ( + self.strip(r) == '' + 'foo@example.com' ) def test_add_number(self): - """ add a number to a dial """ + """add a number to a dial""" d = Dial() - d.number('1231231234') + d.number("1231231234") r = VoiceResponse() r.append(d) - assert_equal( - self.strip(r), - '1231231234' + assert ( + self.strip(r) + == '1231231234' ) def test_add_number_status_callback_event(self): - """ add a number to a dial with status callback events""" + """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') + d.number( + "1231231234", + status_callback="http://example.com", + status_callback_event="initiated completed", + ) r = VoiceResponse() r.append(d) - assert_equal( - self.strip(r), - '1231231234' + assert ( + self.strip(r) == '' + '1231231234' + "" ) def test_add_conference(self): - """ add a conference to a dial """ + """add a conference to a dial""" d = Dial() - d.conference('My Room') + d.conference("My Room") r = VoiceResponse() r.append(d) - assert_equal( - self.strip(r), - 'My Room' + assert ( + self.strip(r) + == 'My Room' ) def test_add_queue(self): - """ add a queue to a dial """ + """add a queue to a dial""" d = Dial() - d.queue('The Cute Queue') + d.queue("The Cute Queue") r = VoiceResponse() r.append(d) - assert_equal( - self.strip(r), - 'The Cute Queue' + assert ( + self.strip(r) + == 'The Cute Queue' ) def test_add_empty_client(self): - """ add an empty client to a dial """ + """add an empty client to a dial""" d = Dial() - d.client('') + d.client("") r = VoiceResponse() r.append(d) - assert_equal( - self.strip(r), - '' + assert ( + self.strip(r) + == '' ) def test_add_client(self): - """ add a client to a dial """ + """add a client to a dial""" d = Dial() - d.client('alice') + d.client("alice") r = VoiceResponse() r.append(d) - assert_equal( - self.strip(r), - 'alice' + assert ( + self.strip(r) + == 'alice' ) class TestGather(TwilioTest): - def test_empty(self): - """ a gather with nothing inside """ + """a gather with nothing inside""" r = VoiceResponse() r.gather() - assert_equal( - self.strip(r), - '' + assert ( + self.strip(r) + == '' ) def test_gather_say(self): g = Gather() - g.say('Hello') + g.say("Hello") r = VoiceResponse() r.append(g) - assert_equal( - self.strip(r), - 'Hello' + assert ( + self.strip(r) + == 'Hello' ) def test_nested_say_play_pause(self): - """ a gather with a say, play, and pause """ + """a gather with a say, play, and pause""" g = Gather() - g.say('Hey') - g.play(url='hey.mp3') + g.say("Hey") + g.play(url="hey.mp3") g.pause() r = VoiceResponse() r.append(g) - assert_equal( - self.strip(r), - 'Heyhey.mp3' + assert ( + self.strip(r) + == 'Heyhey.mp3' + "" + ) + + +class TestText(TwilioTest): + def test_text(self): + r = VoiceResponse() + r.append("No tags!") + + assert ( + self.strip(r) + == 'No tags!' + ) + + def text_mixed(self): + r = VoiceResponse() + r.append("before") + r.say("Content") + r.append("after") + + assert ( + self.strip(r) + == 'beforeContentafter' + ) + + 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) + == '' + "Kindle" ) diff --git a/tox.ini b/tox.ini index 3001f8a2a7..7db6cfc6fc 100644 --- a/tox.ini +++ b/tox.ini @@ -1,8 +1,9 @@ [tox] -envlist = py27, py33, py34, py35, py36, pypy +env_list = py3{7,8,9,10,11}, pypy +skip_missing_interpreters = true [testenv] -deps= -r{toxinidir}/tests/requirements.txt -commands= - nosetests \ - [] +deps = -r{tox_root}/tests/requirements.txt +commands = + pytest \ + [] diff --git a/twilio/__init__.py b/twilio/__init__.py index 71f2c2f090..5ce3ed13d0 100644 --- a/twilio/__init__.py +++ b/twilio/__init__.py @@ -1,3 +1,2 @@ - -__version_info__ = ('6', '12', '0') -__version__ = '.'.join(__version_info__) +__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/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 "".format(self.account_sid) diff --git a/twilio/base/deserialize.py b/twilio/base/deserialize.py index ef6370d628..71226c08f8 100644 --- a/twilio/base/deserialize.py +++ b/twilio/base/deserialize.py @@ -1,13 +1,13 @@ import datetime -from decimal import Decimal, BasicContext +from decimal import BasicContext, Decimal from email.utils import parsedate -import pytz +from typing import Optional, Union -ISO8601_DATE_FORMAT = '%Y-%m-%d' -ISO8601_DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ' +ISO8601_DATE_FORMAT = "%Y-%m-%d" +ISO8601_DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ" -def iso8601_date(s): +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. @@ -15,25 +15,32 @@ def iso8601_date(s): :return: """ try: - return datetime.datetime.strptime(s, ISO8601_DATE_FORMAT).replace(tzinfo=pytz.utc).date() + return ( + datetime.datetime.strptime(s, ISO8601_DATE_FORMAT) + .replace(tzinfo=datetime.timezone.utc) + .date() + ) except (TypeError, ValueError): return s -def iso8601_datetime(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) - :return: datetime or str """ try: - return datetime.datetime.strptime(s, ISO8601_DATETIME_FORMAT).replace(tzinfo=pytz.utc) + return datetime.datetime.strptime(s, ISO8601_DATETIME_FORMAT).replace( + tzinfo=datetime.timezone.utc + ) except (TypeError, ValueError): return s -def rfc2822_datetime(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. @@ -43,21 +50,20 @@ def rfc2822_datetime(s): date_tuple = parsedate(s) if date_tuple is None: return None - return datetime.datetime(*date_tuple[:6]).replace(tzinfo=pytz.utc) + return datetime.datetime(*date_tuple[:6]).replace(tzinfo=datetime.timezone.utc) -def decimal(d): +def decimal(d: Optional[str]) -> Union[Decimal, str]: """ Parses a decimal string into a Decimal :param d: decimal string - :return: Decimal """ if not d: return d return Decimal(d, BasicContext) -def integer(i): +def integer(i: str) -> Union[int, str]: """ Parses an integer string into an int :param i: integer string diff --git a/twilio/base/domain.py b/twilio/base/domain.py index 459c1dfef3..4f8395ddf2 100644 --- a/twilio/base/domain.py +++ b/twilio/base/domain.py @@ -1,37 +1,48 @@ +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): - """ - :param Twilio twilio: - :return: - """ + + def __init__(self, twilio: Client, base_url: str): self.twilio = twilio - self.base_url = None + self.base_url = base_url - def absolute_url(self, uri): + 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('/')) + return "{}/{}".format(self.base_url.strip("/"), uri.strip("/")) - def request(self, method, uri, params=None, data=None, headers=None, - auth=None, timeout=None, allow_redirects=False): + 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 string method: The HTTP method. - :param string uri: The HTTP uri. - :param dict params: Query parameters. - :param object data: The request body. - :param dict headers: The HTTP headers. - :param tuple auth: Basic auth tuple of (username, password) - :param int timeout: The request timeout. - :param bool allow_redirects: True if the client should follow HTTP + :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) @@ -43,6 +54,40 @@ def request(self, method, uri, params=None, data=None, headers=None, headers=headers, auth=auth, timeout=timeout, - allow_redirects=allow_redirects + 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 index 8e2cf20b48..8f3b7cc7a1 100644 --- a/twilio/base/exceptions.py +++ b/twilio/base/exceptions.py @@ -1,7 +1,6 @@ # -*- coding: utf-8 -*- import sys - -from six import u +from typing import Optional class TwilioException(Exception): @@ -9,60 +8,75 @@ class TwilioException(Exception): class TwilioRestException(TwilioException): - """ A generic 400 or 500 level exception from the Twilio API + """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 str method: The HTTP method used to make the request :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, uri, msg="", code=None, method='GET'): + 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): - """ Try to pretty-print the exception, if this is going on screen. """ + def __str__(self) -> str: + """Try to pretty-print the exception, if this is going on screen.""" - def red(words): - return u("\033[31m\033[49m%s\033[0m") % words + def red(words: str) -> str: + return "\033[31m\033[49m%s\033[0m" % words - def white(words): - return u("\033[37m\033[49m%s\033[0m") % words + def white(words: str) -> str: + return "\033[37m\033[49m%s\033[0m" % words - def blue(words): - return u("\033[34m\033[49m%s\033[0m") % words + def blue(words: str) -> str: + return "\033[34m\033[49m%s\033[0m" % words - def teal(words): - return u("\033[36m\033[49m%s\033[0m") % words + def teal(words: str) -> str: + return "\033[36m\033[49m%s\033[0m" % words - def get_uri(code): + 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(): + 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)) - )) + 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))), - ]) + 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 index 3ccfa3a96c..44ff9a384b 100644 --- a/twilio/base/instance_context.py +++ b/twilio/base/instance_context.py @@ -1,8 +1,6 @@ +from twilio.base.version import Version + + class InstanceContext(object): - def __init__(self, version): - """ - :param Version version: - """ + def __init__(self, version: Version): self._version = version - """ :type: Version """ - diff --git a/twilio/base/instance_resource.py b/twilio/base/instance_resource.py index bbb433f42e..a05aac373e 100644 --- a/twilio/base/instance_resource.py +++ b/twilio/base/instance_resource.py @@ -1,8 +1,6 @@ +from twilio.base.version import Version + + class InstanceResource(object): - def __init__(self, version): - """ - :param Version version: - """ + def __init__(self, version: Version): self._version = version - """ :type: Version """ - diff --git a/twilio/base/list_resource.py b/twilio/base/list_resource.py index 823c842a9e..e3eb176d96 100644 --- a/twilio/base/list_resource.py +++ b/twilio/base/list_resource.py @@ -1,7 +1,6 @@ +from twilio.base.version import Version + + class ListResource(object): - def __init__(self, version): - """ - :param Version version: - """ + def __init__(self, version: Version): self._version = version - """ :type: Version """ diff --git a/twilio/base/obsolete.py b/twilio/base/obsolete.py index 6c89ba86dd..e0f4a0339d 100644 --- a/twilio/base/obsolete.py +++ b/twilio/base/obsolete.py @@ -2,9 +2,8 @@ import functools -class ObsoleteException(BaseException): - """ Base class for warnings about obsolete features. """ - pass +class ObsoleteException(Exception): + """Base class for warnings about obsolete features.""" def obsolete_client(func): @@ -16,8 +15,33 @@ def obsolete_client(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__) + "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 index e355c18680..b5b2da7b26 100644 --- a/twilio/base/page.py +++ b/twilio/base/page.py @@ -1,6 +1,8 @@ import json +from typing import Any, Dict, Optional from twilio.base.exceptions import TwilioException +from twilio.http.response import Response class Page(object): @@ -10,26 +12,27 @@ class Page(object): 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' + "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): + def __init__(self, version, response: Response, solution={}): payload = self.process_response(response) self._version = version self._payload = payload - self._solution = {} + self._solution = solution self._records = iter(self.load_page(payload)) def __iter__(self): @@ -48,89 +51,123 @@ def next(self): return self.get_instance(next(self._records)) @classmethod - def process_response(self, response): + def process_response(cls, response: Response) -> Any: """ Load a JSON response. - :param Response response: The HTTP response. - :return dict: The JSON-loaded content. + :param response: The HTTP response. + :return The JSON-loaded content. """ if response.status_code != 200: - raise TwilioException('Unable to fetch page', response) + raise TwilioException("Unable to fetch page", response) return json.loads(response.text) - def load_page(self, payload): + def load_page(self, payload: Dict[str, Any]): """ Parses the collection of records out of a list payload. - :param dict payload: The JSON-loaded content. + :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']] + 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') + raise TwilioException("Page Records can not be deserialized") @property - def previous_page_url(self): + 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']) + 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): + 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']) + 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): + 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') + raise TwilioException( + "Page.get_instance() must be implemented in the derived class" + ) - def next_page(self): + def next_page(self) -> Optional["Page"]: """ Return the `Page` after this one. - :return Page: The next page. + :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 = self._version.domain.twilio.request('GET', self.next_page_url) + 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): + def previous_page(self) -> Optional["Page"]: """ Return the `Page` before this one. - :return Page: The previous page. + :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 = self._version.domain.twilio.request('GET', self.previous_page_url) + 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): - return '' + def __repr__(self) -> str: + return "" diff --git a/twilio/base/serialize.py b/twilio/base/serialize.py index c0fcf1023f..cea91b04c7 100644 --- a/twilio/base/serialize.py +++ b/twilio/base/serialize.py @@ -27,7 +27,7 @@ def iso8601_datetime(d): 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') + return d.strftime("%Y-%m-%dT%H:%M:%SZ") elif isinstance(d, str): return d @@ -39,22 +39,41 @@ def prefixed_collapsible_map(m, prefix): if m == values.unset: return {} - def flatten_dict(d, result={}, prv_keys=[]): + 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 + 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 {"{}.{}".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 @@ -72,4 +91,3 @@ def map(lst, serialize_func): 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 index f2421c3a7f..16032b1120 100644 --- a/twilio/base/values.py +++ b/twilio/base/values.py @@ -1,12 +1,13 @@ -from six import iteritems +from typing import Dict + unset = object() -def of(d): +def of(d: Dict[str, object]) -> Dict[str, object]: """ Remove unset values from a dict. - :param dict d: A dict to strip. - :return dict: A dict with unset values removed. + :param d: A dict to strip. + :return A dict with unset values removed. """ - return {k: v for k, v in iteritems(d) if v != unset} + return {k: v for k, v in d.items() if v != unset} diff --git a/twilio/base/version.py b/twilio/base/version.py index 51c1bd5da9..ed7e86f499 100644 --- a/twilio/base/version.py +++ b/twilio/base/version.py @@ -1,8 +1,11 @@ import json -from math import ceil +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): @@ -10,28 +13,33 @@ class Version(object): Represents an API version. """ - def __init__(self, domain): - """ - :param Domain domain: - :return: - """ + def __init__(self, domain: Domain, version: str): self.domain = domain - self.version = None + self.version = version - def absolute_url(self, uri): + 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): + 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, uri, params=None, data=None, headers=None, - auth=None, timeout=None, allow_redirects=False): + 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. """ @@ -44,26 +52,78 @@ def request(self, method, uri, params=None, data=None, headers=None, headers=headers, auth=auth, timeout=timeout, - allow_redirects=allow_redirects + 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, uri, response, message): + 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']) - code = error_payload.get('code', response.status_code) - return TwilioRestException(response.status_code, uri, message, code, method) + 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) + 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, uri, params=None, data=None, headers=None, auth=None, timeout=None, - allow_redirects=False): + 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. """ @@ -78,13 +138,54 @@ def fetch(self, method, uri, params=None, data=None, headers=None, auth=None, ti 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 fetch record') + raise self.exception(method, uri, response, "Unable to update record") return json.loads(response.text) - def update(self, method, uri, params=None, data=None, headers=None, auth=None, timeout=None, - allow_redirects=False): + 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. """ @@ -99,13 +200,55 @@ def update(self, method, uri, params=None, data=None, headers=None, auth=None, t 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 update record') + raise self.exception(method, uri, response, "Unable to delete record") - return json.loads(response.text) + return response.status_code == 204 - def delete(self, method, uri, params=None, data=None, headers=None, auth=None, timeout=None, - allow_redirects=False): + 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. """ @@ -120,37 +263,65 @@ def delete(self, method, uri, params=None, data=None, headers=None, auth=None, t allow_redirects=allow_redirects, ) - if response.status_code < 200 or response.status_code >= 300: - raise self.exception(method, uri, response, 'Unable to delete record') + 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 response.status_code == 204 + return self._parse_delete(method, uri, response) - def read_limits(self, limit=None, page_size=None): + 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 int limit: Max number of records to read. - :param int page_size: Max page size. - :return dict: A dictionary of paging limits. + :param limit: Max number of records to read. + :param page_size: Max page size. + :return A dictionary of paging limits. """ - page_limit = values.unset - - if limit is not None: - - if page_size is None: - page_size = limit - - page_limit = int(ceil(limit / float(page_size))) + 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, - 'page_limit': page_limit, + "limit": limit or values.unset, + "page_size": page_size or values.unset, } - def page(self, method, uri, params=None, data=None, headers=None, auth=None, timeout=None, - allow_redirects=False): + 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. """ @@ -165,13 +336,43 @@ def page(self, method, uri, params=None, data=None, headers=None, auth=None, tim allow_redirects=allow_redirects, ) - def stream(self, page, limit=None, page_limit=None): + 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 page: The page to stream. - :param int limit: The max number of records to read. - :param int page_imit: The max number of pages to read. + :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 @@ -183,14 +384,69 @@ def stream(self, page, limit=None, page_limit=None): if limit and limit is not values.unset and limit < current_record: return - if page_limit and page_limit is not values.unset and page_limit < current_page: + 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, uri, params=None, data=None, headers=None, auth=None, timeout=None, - allow_redirects=False): + 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. """ @@ -204,8 +460,30 @@ def create(self, method, uri, params=None, data=None, headers=None, auth=None, t timeout=timeout, allow_redirects=allow_redirects, ) - - 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) + 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.py b/twilio/compat.py deleted file mode 100644 index 3a800e460a..0000000000 --- a/twilio/compat.py +++ /dev/null @@ -1,17 +0,0 @@ -# Those are not supported by the six library and needs to be done manually -try: - # python 3 - from urllib.parse import urlencode, urlparse, urljoin, urlunparse -except ImportError: - # python 2 backward compatibility - # noinspection PyUnresolvedReferences - from urllib import urlencode - # noinspection PyUnresolvedReferences - from urlparse import urlparse, urljoin, urlunparse - -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 index a0360a2d11..3e24827035 100644 --- a/twilio/http/__init__.py +++ b/twilio/http/__init__.py @@ -1,13 +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, url, params=None, data=None, headers=None, auth=None, - timeout=None, allow_redirects=False): + + 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') + 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 index dff16a99a4..2f2d363535 100644 --- a/twilio/http/http_client.py +++ b/twilio/http/http_client.py @@ -1,75 +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.response import Response from twilio.http.request import Request as TwilioRequest -import logging -from twilio.compat import urlencode +from twilio.http.response import Response -_logger = logging.getLogger('twilio.http_client') +_logger = logging.getLogger("twilio.http_client") class TwilioHttpClient(HttpClient): """ General purpose HTTP Client for interacting with the Twilio API """ - def __init__(self, pool_connections=True, request_hooks=None): + + 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 - self.last_request = None - self.last_response = 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, url, params=None, data=None, headers=None, auth=None, timeout=None, - allow_redirects=False): + 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 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 + :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 - :rtype: A :class:`Response ` object + :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, - 'data': data, - 'headers': headers, - 'auth': auth, - 'hooks': self.request_hooks + "method": method.upper(), + "url": url, + "params": params, + "headers": headers, + "auth": auth, + "hooks": self.request_hooks, } - - if params: - _logger.info('{method} Request: {url}?{query}'.format(query=urlencode(params), **kwargs)) - _logger.info('PARAMS: {params}'.format(**kwargs)) + 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: - _logger.info('{method} Request: {url}'.format(**kwargs)) - if data: - _logger.info('PAYLOAD: {data}'.format(**kwargs)) - - self.last_response = None + kwargs["data"] = data + self.log_request(kwargs) + self._test_only_last_response = None session = self.session or Session() request = Request(**kwargs) - self.last_request = TwilioRequest(**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, ) - _logger.info('{method} Response: {status} {text}'.format(method=method, status=response.status_code, text=response.text)) + self.log_response(response.status_code, response) - self.last_response = Response(int(response.status_code), response.text) + self._test_only_last_response = Response( + int(response.status_code), response.text, response.headers + ) - return self.last_response + 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 index e96528dcff..e75cf12b0d 100644 --- a/twilio/http/request.py +++ b/twilio/http/request.py @@ -1,21 +1,30 @@ -from twilio.compat import urlencode +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. """ - ANY = '*' - - def __init__(self, - method=ANY, - url=ANY, - auth=ANY, - params=ANY, - data=ANY, - headers=ANY, - **kwargs): - self.method = method.upper() + + 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 @@ -23,8 +32,8 @@ def __init__(self, self.headers = headers @classmethod - def attribute_equal(cls, lhs, rhs): - if lhs == cls.ANY or rhs == cls.ANY: + def attribute_equal(cls, lhs, rhs) -> bool: + if lhs == Match.ANY or rhs == Match.ANY: # ANY matches everything return True @@ -33,38 +42,43 @@ def attribute_equal(cls, lhs, rhs): return lhs == rhs - def __eq__(self, other): + 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): - auth = '' - if self.auth and self.auth != self.ANY: - auth = '{} '.format(self.auth) - - params = '' - if self.params and self.params != self.ANY: - params = '?{}'.format(urlencode(self.params, doseq=True)) - - data = '' - if self.data and self.data != self.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 != self.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( + 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, @@ -73,5 +87,5 @@ def __str__(self): headers=headers, ) - def __repr__(self): + def __repr__(self) -> str: return str(self) diff --git a/twilio/http/response.py b/twilio/http/response.py index a778a8a2d4..af5a3b1706 100644 --- a/twilio/http/response.py +++ b/twilio/http/response.py @@ -1,16 +1,22 @@ -class Response(object): - """ +from typing import Any, Optional + - """ - def __init__(self, status_code, text): +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): + def text(self) -> str: return self.content - def __repr__(self): - return 'HTTP {} {}'.format(self.status_code, 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 index f10a7750c3..1a4a83f0a5 100644 --- a/twilio/http/validation_client.py +++ b/twilio/http/validation_client.py @@ -2,20 +2,30 @@ from requests import Request, Session -from twilio.compat import urlparse +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']) +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): + __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. @@ -32,8 +42,17 @@ def __init__(self, account_sid, api_key_sid, credential_sid, private_key, pool_c 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): + def request( + self, + method, + url, + params=None, + data=None, + headers=None, + auth=None, + timeout=None, + allow_redirects=False, + ): """ Make a signed HTTP Request @@ -51,16 +70,26 @@ def request(self, method, url, params=None, data=None, headers=None, auth=None, :rtype: A :class:`Response ` object """ session = self.session or Session() - request = Request(method.upper(), url, params=params, data=data, headers=headers, auth=auth) + 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) + 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() + 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, @@ -78,7 +107,7 @@ def _build_validation_payload(self, request): """ parsed = urlparse(request.url) path = parsed.path - query_string = parsed.query or '' + query_string = parsed.query or "" return ValidationPayload( method=request.method, @@ -86,10 +115,24 @@ def _build_validation_payload(self, request): query_string=query_string, all_headers=request.headers, signed_headers=ValidationClient.__SIGNED_HEADERS, - body=request.body or '' + body=request.body or "", ) def _get_host(self, request): """Pull the Host out of the request""" parsed = urlparse(request.url) - return parsed.netloc + 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 32aeb2d544..7a51ea70d5 100644 --- a/twilio/jwt/__init__.py +++ b/twilio/jwt/__init__.py @@ -1,23 +1,8 @@ -import hmac -import sys - -from twilio.jwt import compat - -if sys.version_info[0] == 3 and sys.version_info[1] == 2: - # PyJWT expects hmac.compare_digest to exist even under python 3.2 - hmac.compare_digest = compat.compare_digest - import jwt as jwt_lib - -try: - import json -except ImportError: - import simplejson as json - import time -__all__ = ['Jwt', 'JwtDecodeError'] +__all__ = ["Jwt", "JwtDecodeError"] class JwtDecodeError(Exception): @@ -26,17 +11,27 @@ class JwtDecodeError(Exception): class Jwt(object): """Base class for building a Json Web Token""" - GENERATE = object() - def __init__(self, secret_key, issuer, subject=None, algorithm='HS256', nbf=GENERATE, - ttl=3600, valid_until=None): + 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, ommited from payload by default""" - self.algorithm = algorithm + """: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.""" @@ -50,7 +45,7 @@ def __init__(self, secret_key, issuer, subject=None, algorithm='HS256', nbf=GENE def _generate_payload(self): """:rtype: dict the payload of the JWT to send""" - raise NotImplementedError('Subclass must provide a payload.') + 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""" @@ -65,11 +60,11 @@ def _from_jwt(cls, headers, payload, key=None): """ 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), + 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 @@ -81,17 +76,17 @@ def payload(self): return self.__decoded_payload payload = self._generate_payload().copy() - payload['iss'] = self.issuer - payload['exp'] = int(time.time()) + self.ttl + 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()) + payload["nbf"] = int(time.time()) else: - payload['nbf'] = self.nbf + payload["nbf"] = self.nbf if self.valid_until: - payload['exp'] = self.valid_until + payload["exp"] = self.valid_until if self.subject: - payload['sub'] = self.subject + payload["sub"] = self.subject return payload @@ -101,34 +96,32 @@ def headers(self): return self.__decoded_headers headers = self._generate_headers().copy() - headers['typ'] = 'JWT' - headers['alg'] = self.algorithm + headers["typ"] = "JWT" + headers["alg"] = self.algorithm return headers - def to_jwt(self, algorithm=None, ttl=None): + def to_jwt(self, ttl=None): """ Encode this JWT object into a JWT string - :param str algorithm: override the algorithm used to encode the JWT :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.') + raise ValueError("JWT does not have a signing key configured.") headers = self.headers.copy() - if algorithm: - headers['alg'] = algorithm - algorithm = algorithm or self.algorithm payload = self.payload.copy() if ttl: - payload['exp'] = int(time.time()) + ttl + payload["exp"] = int(time.time()) + ttl - return jwt_lib.encode(payload, self.secret_key, algorithm=algorithm, headers=headers) + return jwt_lib.encode( + payload, self.secret_key, algorithm=self.algorithm, headers=headers + ) @classmethod - def from_jwt(cls, jwt, key=''): + def from_jwt(cls, jwt, key=""): """ Decode a JWT string into a Jwt object :param str jwt: JWT string @@ -140,16 +133,29 @@ def from_jwt(cls, jwt, key=''): verify = True if key else False try: - payload = jwt_lib.decode(bytes(jwt), key, options={ - 'verify_signature': verify, - 'verify_exp': True, - 'verify_nbf': True, - }) 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))) + raise JwtDecodeError(getattr(e, "message", str(e))) return cls._from_jwt(headers, payload, key) def __str__(self): - return ''.format(self.to_jwt()) + return "".format(self.to_jwt()) diff --git a/twilio/jwt/access_token/__init__.py b/twilio/jwt/access_token/__init__.py index 4e542a5f8b..764b2a028c 100644 --- a/twilio/jwt/access_token/__init__.py +++ b/twilio/jwt/access_token/__init__.py @@ -5,34 +5,49 @@ 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.') + raise NotImplementedError("Grant must have a key property.") def to_payload(self): """:return: dict something""" - raise NotImplementedError('Grant must implement to_payload.') + raise NotImplementedError("Grant must implement to_payload.") def __str__(self): - '<{} {}>'.format(self.__class__.__name__, self.to_payload()) + return "<{} {}>".format(self.__class__.__name__, self.to_payload()) class AccessToken(Jwt): """Access Token containing one or more AccessTokenGrants used to access Twilio Resources""" - def __init__(self, account_sid, signing_key_sid, secret, grants=None, - identity=None, nbf=Jwt.GENERATE, ttl=3600, valid_until=None): + + 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.') + 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='HS256', + algorithm=self.ALGORITHM, issuer=signing_key_sid, subject=self.account_sid, nbf=nbf, @@ -43,23 +58,24 @@ def __init__(self, account_sid, signing_key_sid, secret, grants=None, 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.') + raise ValueError("Grant must be an instance of AccessTokenGrant.") self.grants.append(grant) def _generate_headers(self): - return { - 'cty': 'twilio-fpa;v=1' - } + 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} + "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 + payload["grants"]["identity"] = self.identity return payload def __str__(self): - return ''.format(self.to_jwt()) + return "<{} {}>".format(self.__class__.__name__, self.to_jwt()) diff --git a/twilio/jwt/access_token/grants.py b/twilio/jwt/access_token/grants.py index 1f42b6e56b..16d19aa383 100644 --- a/twilio/jwt/access_token/grants.py +++ b/twilio/jwt/access_token/grants.py @@ -4,15 +4,19 @@ def deprecated(func): - '''This is a decorator which can be used to mark functions + """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.''' + 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) + 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 @@ -21,8 +25,13 @@ def new_func(*args, **kwargs): 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): + 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 @@ -35,48 +44,20 @@ def key(self): def to_payload(self): grant = {} if self.service_sid: - grant['service_sid'] = self.service_sid + grant["service_sid"] = self.service_sid if self.endpoint_id: - grant['endpoint_id'] = self.endpoint_id + grant["endpoint_id"] = self.endpoint_id if self.deployment_role_sid: - grant['deployment_role_sid'] = 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 IpMessagingGrant(AccessTokenGrant): - """Grant to access Twilio IP Messaging""" - - @deprecated - 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 "ip_messaging" - - 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 + 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 @@ -88,21 +69,24 @@ def key(self): def to_payload(self): grant = {} if self.service_sid: - grant['service_sid'] = self.service_sid + grant["service_sid"] = self.service_sid if self.endpoint_id: - grant['endpoint_id'] = 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): + + 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 @@ -121,45 +105,28 @@ def key(self): def to_payload(self): grant = {} if self.incoming_allow is True: - grant['incoming'] = {} - grant['incoming']['allow'] = True + grant["incoming"] = {} + grant["incoming"]["allow"] = True if self.outgoing_application_sid: - grant['outgoing'] = {} - grant['outgoing']['application_sid'] = 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 + grant["outgoing"]["params"] = self.outgoing_application_params if self.push_credential_sid: - grant['push_credential_sid'] = 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 ConversationsGrant(AccessTokenGrant): - """Grant to access Twilio Conversations""" - @deprecated - def __init__(self, configuration_profile_sid=None): - self.configuration_profile_sid = configuration_profile_sid - - @property - def key(self): - return "rtc" - - def to_payload(self): - grant = {} - if self.configuration_profile_sid: - grant['configuration_profile_sid'] = self.configuration_profile_sid + grant["endpoint_id"] = self.endpoint_id return grant class VideoGrant(AccessTokenGrant): """Grant to access Twilio Video""" + def __init__(self, room=None): self.room = room @@ -170,13 +137,14 @@ def key(self): def to_payload(self): grant = {} if self.room: - grant['room'] = 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 @@ -189,10 +157,27 @@ def key(self): def to_payload(self): grant = {} if self.workspace_sid: - grant['workspace_sid'] = self.workspace_sid + grant["workspace_sid"] = self.workspace_sid if self.worker_sid: - grant['worker_sid'] = self.worker_sid + grant["worker_sid"] = self.worker_sid if self.role: - grant['role'] = 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 index be0ede910b..d5c38c4729 100644 --- a/twilio/jwt/client/__init__.py +++ b/twilio/jwt/client/__init__.py @@ -1,14 +1,22 @@ from twilio.jwt import Jwt -from six import iteritems -from twilio.compat import urlencode +from urllib.parse import urlencode class ClientCapabilityToken(Jwt): """A token to control permissions with Twilio Client""" - def __init__(self, account_sid, auth_token, nbf=Jwt.GENERATE, ttl=3600, valid_until=None, - **kwargs): + 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 @@ -21,7 +29,7 @@ def __init__(self, account_sid, auth_token, nbf=Jwt.GENERATE, ttl=3600, valid_un :returns: A new CapabilityToken with zero permissions """ super(ClientCapabilityToken, self).__init__( - algorithm='HS256', + algorithm=self.ALGORITHM, secret_key=auth_token, issuer=account_sid, nbf=nbf, @@ -34,12 +42,12 @@ def __init__(self, account_sid, auth_token, nbf=Jwt.GENERATE, ttl=3600, valid_un 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']) + 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): """ @@ -48,11 +56,11 @@ def allow_client_outgoing(self, application_sid, **kwargs): :param str application_sid: Application to contact """ - scope = ScopeURI('client', 'outgoing', {'appSid': application_sid}) + scope = ScopeURI("client", "outgoing", {"appSid": application_sid}) if kwargs: - scope.add_param('appParams', urlencode(kwargs, doseq=True)) + scope.add_param("appParams", urlencode(kwargs, doseq=True)) - self.capabilities['outgoing'] = scope + self.capabilities["outgoing"] = scope def allow_client_incoming(self, client_name): """ @@ -61,24 +69,28 @@ def allow_client_incoming(self, client_name): :param str client_name: Client name to accept calls from """ self.client_name = client_name - self.capabilities['incoming'] = ScopeURI('client', 'incoming', {'clientName': 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'}) + scope = ScopeURI("stream", "subscribe", {"path": "/2010-04-01/Events"}) if kwargs: - scope.add_param('params', urlencode(kwargs, doseq=True)) + 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) + 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)} + scope_uris = [ + scope_uri.to_payload() for scope_uri in self.capabilities.values() + ] + return {"scope": " ".join(scope_uris)} class ScopeURI(object): @@ -94,12 +106,12 @@ def add_param(self, key, value): def to_payload(self): if self.params: - sorted_params = sorted([(k, v) for k, v in iteritems(self.params)]) + sorted_params = sorted([(k, v) for k, v in self.params.items()]) encoded_params = urlencode(sorted_params) - param_string = '?{}'.format(encoded_params) + param_string = "?{}".format(encoded_params) else: - param_string = '' - return 'scope:{}:{}{}'.format(self.service, self.privilege, param_string) + param_string = "" + return "scope:{}:{}{}".format(self.service, self.privilege, param_string) def __str__(self): - return ''.format(self.to_payload()) + return "".format(self.to_payload()) diff --git a/twilio/jwt/compat.py b/twilio/jwt/compat.py deleted file mode 100644 index f0237c2f72..0000000000 --- a/twilio/jwt/compat.py +++ /dev/null @@ -1,25 +0,0 @@ -def compare_digest(a, b): - """ - PyJWT expects hmac.compare_digest to exist for all Python 3.x, however it was added in Python > 3.3 - It has a fallback for Python 2.x but not for Pythons between 2.x and 3.3 - Copied from: https://github.com/python/cpython/commit/6cea65555caf2716b4633827715004ab0291a282#diff-c49659257ec1b129707ce47a98adc96eL16 - - Returns the equivalent of 'a == b', but avoids content based short - circuiting to reduce the vulnerability to timing attacks. - """ - # Consistent timing matters more here than data type flexibility - if not (isinstance(a, bytes) and isinstance(b, bytes)): - raise TypeError("inputs must be bytes instances") - - # We assume the length of the expected digest is public knowledge, - # thus this early return isn't leaking anything an attacker wouldn't - # already know - if len(a) != len(b): - return False - - # We assume that integers in the bytes range are all cached, - # thus timing shouldn't vary much due to integer object creation - result = 0 - for x, y in zip(a, b): - result |= x ^ y - return result == 0 diff --git a/twilio/jwt/taskrouter/__init__.py b/twilio/jwt/taskrouter/__init__.py index 3095ae73a7..5a01560dfa 100644 --- a/twilio/jwt/taskrouter/__init__.py +++ b/twilio/jwt/taskrouter/__init__.py @@ -2,9 +2,10 @@ class TaskRouterCapabilityToken(Jwt): - VERSION = 'v1' - DOMAIN = 'https://taskrouter.twilio.com' - EVENTS_BASE_URL = 'https://event-bridge.twilio.com/v1/wschannels' + 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): """ @@ -28,10 +29,10 @@ def __init__(self, account_sid, auth_token, workspace_sid, channel_id, **kwargs) super(TaskRouterCapabilityToken, self).__init__( secret_key=auth_token, issuer=account_sid, - algorithm='HS256', - nbf=kwargs.get('nbf', Jwt.GENERATE), - ttl=kwargs.get('ttl', 3600), - valid_until=kwargs.get('valid_until', None), + 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) @@ -42,93 +43,100 @@ def __init__(self, account_sid, auth_token, workspace_sid, channel_id, **kwargs) self.channel_id = channel_id self.policies = [] - if kwargs.get('allow_web_sockets', True): + if kwargs.get("allow_web_sockets", True): self.allow_web_sockets() - if kwargs.get('allow_fetch_self', True): + if kwargs.get("allow_fetch_self", True): self.allow_fetch_self() - if kwargs.get('allow_update_self', False): + if kwargs.get("allow_update_self", False): self.allow_update_self() - if kwargs.get('allow_delete_self', False): + if kwargs.get("allow_delete_self", False): self.allow_delete_self() - if kwargs.get('allow_fetch_subresources', False): + if kwargs.get("allow_fetch_subresources", False): self.allow_fetch_subresources() - if kwargs.get('allow_delete_subresources', False): + if kwargs.get("allow_delete_subresources", False): self.allow_delete_subresources() - if kwargs.get('allow_update_subresources', False): + 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) + return "{}/{}/Workspaces/{}".format( + self.DOMAIN, self.VERSION, self.workspace_sid + ) @property def resource_url(self): - raise NotImplementedError('Subclass must set its specific resource_url.') + 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.') + raise NotImplementedError( + "Subclass must set its specific channel_id sid prefix." + ) def allow_fetch_self(self): - self._make_policy(self.resource_url, 'GET', True) + self._make_policy(self.resource_url, "GET", True) def allow_update_self(self): - self._make_policy(self.resource_url, 'POST', True) + self._make_policy(self.resource_url, "POST", True) def allow_delete_self(self): - self._make_policy(self.resource_url, 'DELETE', True) + self._make_policy(self.resource_url, "DELETE", True) def allow_fetch_subresources(self): - self._make_policy(self.resource_url + '/**', 'GET', True) + self._make_policy(self.resource_url + "/**", "GET", True) def allow_update_subresources(self): - self._make_policy(self.resource_url + '/**', 'POST', True) + self._make_policy(self.resource_url + "/**", "POST", True) def allow_delete_subresources(self): - self._make_policy(self.resource_url + '/**', 'DELETE', True) + 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) + 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, + "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 + 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 {}, - }) + 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 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 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)) + raise ValueError("Invalid channel id provided {}".format(channel_id)) def __str__(self): - return ''.format(self.to_jwt()) - + return "".format(self.to_jwt()) diff --git a/twilio/jwt/taskrouter/capabilities.py b/twilio/jwt/taskrouter/capabilities.py index 0f4cb8cb91..468a027016 100644 --- a/twilio/jwt/taskrouter/capabilities.py +++ b/twilio/jwt/taskrouter/capabilities.py @@ -2,7 +2,9 @@ class WorkerCapabilityToken(TaskRouterCapabilityToken): - def __init__(self, account_sid, auth_token, workspace_sid, worker_sid, ttl=3600, **kwargs): + def __init__( + self, account_sid, auth_token, workspace_sid, worker_sid, ttl=3600, **kwargs + ): """ :param kwargs: All kwarg parameters supported by TaskRouterCapabilityToken @@ -26,48 +28,50 @@ def __init__(self, account_sid, auth_token, workspace_sid, worker_sid, ttl=3600, **kwargs ) - if kwargs.get('allow_fetch_activities', True): + if kwargs.get("allow_fetch_activities", True): self.allow_fetch_activities() - if kwargs.get('allow_fetch_reservations', True): + if kwargs.get("allow_fetch_reservations", True): self.allow_fetch_reservations() - if kwargs.get('allow_fetch_worker_reservations', True): + if kwargs.get("allow_fetch_worker_reservations", True): self.allow_fetch_worker_reservations() - if kwargs.get('allow_update_activities', False): + if kwargs.get("allow_update_activities", False): self.allow_update_activities() - if kwargs.get('allow_update_reservations', False): + 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) + return "{}/Workers/{}".format(self.workspace_url, self.channel_id) @property def channel_prefix(self): - return 'WK' + return "WK" def allow_fetch_activities(self): - self._make_policy(self.workspace_url + '/Activities', 'GET', True) + self._make_policy(self.workspace_url + "/Activities", "GET", True) def allow_fetch_reservations(self): - self._make_policy(self.workspace_url + '/Tasks/**', 'GET', True) + self._make_policy(self.workspace_url + "/Tasks/**", "GET", True) def allow_fetch_worker_reservations(self): - self._make_policy(self.resource_url + '/Reservations/**', 'GET', True) + 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) + 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) + self._make_policy(self.workspace_url + "/Tasks/**", "POST", True) + self._make_policy(self.resource_url + "/Reservations/**", "POST", True) def __str__(self): - return ''.format(self.to_jwt()) + return "".format(self.to_jwt()) class TaskQueueCapabilityToken(TaskRouterCapabilityToken): - def __init__(self, account_sid, auth_token, workspace_sid, task_queue_sid, ttl=3600, **kwargs): + 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, @@ -79,14 +83,14 @@ def __init__(self, account_sid, auth_token, workspace_sid, task_queue_sid, ttl=3 @property def resource_url(self): - return '{}/TaskQueues/{}'.format(self.workspace_url, self.channel_id) + return "{}/TaskQueues/{}".format(self.workspace_url, self.channel_id) @property def channel_prefix(self): - return 'WQ' + return "WQ" def __str__(self): - return ''.format(self.to_jwt()) + return "".format(self.to_jwt()) class WorkspaceCapabilityToken(TaskRouterCapabilityToken): @@ -106,7 +110,7 @@ def resource_url(self): @property def channel_prefix(self): - return 'WS' + return "WS" def __str__(self): - return ''.format(self.to_jwt()) + return "".format(self.to_jwt()) diff --git a/twilio/jwt/validation/__init__.py b/twilio/jwt/validation/__init__.py index 70c1d41ec4..837d6196e0 100644 --- a/twilio/jwt/validation/__init__.py +++ b/twilio/jwt/validation/__init__.py @@ -1,14 +1,17 @@ from hashlib import sha256 -from six import string_types 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' - def __init__(self, account_sid, api_key_sid, credential_sid, private_key, validation_payload): + __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' @@ -22,35 +25,39 @@ def __init__(self, account_sid, api_key_sid, credential_sid, private_key, valida secret_key=private_key, issuer=api_key_sid, subject=account_sid, - algorithm='RS256', - ttl=300 # 5 minute ttl + 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 - } + 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()} + 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) + 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, '&') + 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 '' + req_body_hash = self._hash(self.validation_payload.body) or "" - signed_headers_str = ';'.join(signed_headers) + signed_headers_str = ";".join(signed_headers) signed_payload = [ self.validation_payload.method, @@ -60,29 +67,26 @@ def _generate_payload(self): if headers_str: signed_payload.append(headers_str) - signed_payload.append('') + signed_payload.append("") signed_payload.append(signed_headers_str) signed_payload.append(req_body_hash) - signed_payload = '\n'.join(signed_payload) + signed_payload = "\n".join(signed_payload) - return { - 'hrh': signed_headers_str, - 'rqh': self._hash(signed_payload) - } + return {"hrh": signed_headers_str, "rqh": self._hash(signed_payload)} @classmethod - def _sort_and_join(self, values, joiner): - if isinstance(values, string_types): + def _sort_and_join(cls, values, joiner): + if isinstance(values, str): return values return joiner.join(sorted(values)) @classmethod - def _hash(self, input_str): + 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') + input_str = input_str.encode("utf-8") return sha256(input_str).hexdigest() diff --git a/twilio/request_validator.py b/twilio/request_validator.py index f798b544f4..f7a0db361c 100644 --- a/twilio/request_validator.py +++ b/twilio/request_validator.py @@ -1,10 +1,8 @@ import base64 import hmac -from hashlib import sha1 +from hashlib import sha1, sha256 -from six import PY3 - -from twilio.compat import izip, urlparse +from urllib.parse import urlparse, parse_qs def compare(string1, string2): @@ -19,48 +17,88 @@ def compare(string1, string2): if len(string1) != len(string2): return False result = True - for c1, c2 in izip(string1, string2): + 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: full URI that Twilio requested on your server + :param uri: parsed URI that Twilio requested on your server :returns: full URI without a port number :rtype: str """ - new_netloc = uri.netloc.split(':')[0] + if not uri.port: + return uri.geturl() + + new_netloc = uri.netloc.split(":")[0] new_uri = uri._replace(netloc=new_netloc) + return new_uri.geturl() -class RequestValidator(object): +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, utf=PY3): + 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 utf: whether return should be bytestring or unicode (python3) :returns: The computed signature """ s = uri - if len(params) > 0: - for k, v in sorted(params.items()): - s += k + v + 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()) - if utf: - computed = computed.decode('utf-8') + 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() @@ -68,12 +106,32 @@ 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 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) - if parsed_uri.scheme == "https" and parsed_uri.port: - uri = remove_port(parsed_uri) - return compare(self.compute_signature(uri, params), signature) + 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 0d10baf71a..823cbbfaa0 100644 --- a/twilio/rest/__init__.py +++ b/twilio/rest/__init__.py @@ -1,599 +1,742 @@ -# coding=utf-8 +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. """ -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -import os -import platform -from twilio import __version__ -from twilio.base.exceptions import TwilioException -from twilio.base.obsolete import obsolete_client -from twilio.http.http_client import TwilioHttpClient - -class Client(object): - """ A client for accessing the Twilio API. """ - - def __init__(self, username=None, password=None, account_sid=None, region=None, - http_client=None, environment=None): +from typing import TYPE_CHECKING, Optional + +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 - :param str password: Password to authenticate with - :param str account_sid: Account Sid, defaults to Username - :param str region: Twilio Region to make requests to + :param 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 """ - environment = environment or os.environ - - self.username = username or environment.get('TWILIO_ACCOUNT_SID') - """ :type : str """ - self.password = password or environment.get('TWILIO_AUTH_TOKEN') - """ :type : str """ - self.account_sid = account_sid or self.username - """ :type : str """ - self.region = region - """ :type : str """ - - if not self.username or not self.password: - raise TwilioException("Credentials are required to create a TwilioClient") - - self.auth = (self.username, self.password) - """ :type : tuple(str, str) """ - self.http_client = http_client or TwilioHttpClient() - """ :type : HttpClient """ - - # Domains - self._accounts = None - self._api = None - self._chat = None - self._fax = None - self._ip_messaging = None - self._lookups = None - self._monitor = None - self._notify = None - self._preview = None - self._pricing = None - self._proxy = None - self._taskrouter = None - self._trunking = None - self._video = None - self._messaging = None - self._wireless = None - self._sync = None - self._studio = None - - def request(self, method, uri, params=None, data=None, headers=None, auth=None, - timeout=None, allow_redirects=False): - """ - Makes a request to the Twilio API using the configured http client - Authentication information is automatically added if none is provided - - :param str method: HTTP Method - :param str uri: Fully qualified url - :param dict[str, str] params: Query string parameters - :param dict[str, str] data: POST body data - :param dict[str, str] headers: HTTP Headers - :param tuple(str, str) auth: Authentication - :param int timeout: Timeout in seconds - :param bool allow_redirects: Should the client follow redirects - - :returns: Response from the Twilio API - :rtype: twilio.http.response.Response - """ - auth = auth or self.auth - headers = headers or {} - - headers['User-Agent'] = 'twilio-python/{} (Python {})'.format( - __version__, - platform.python_version(), - ) - headers['X-Twilio-Client'] = 'python-{}'.format(__version__) - headers['Accept-Charset'] = 'utf-8' - - if method == 'POST' and 'Content-Type' not in headers: - headers['Content-Type'] = 'application/x-www-form-urlencoded' - - if 'Accept' not in headers: - headers['Accept'] = 'application/json' - - if self.region: - head, tail = uri.split('.', 1) - - if not tail.startswith(self.region): - uri = '.'.join([head, self.region, tail]) - - return self.http_client.request( - method, - uri, - params=params, - data=data, - headers=headers, - auth=auth, - timeout=timeout, - allow_redirects=allow_redirects + super().__init__( + username, + password, + account_sid, + region, + http_client, + environment, + edge, + user_agent_extensions, + credential_provider, ) - @property - def accounts(self): + # 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 - :rtype: twilio.rest.accounts.Accounts """ if self._accounts is None: from twilio.rest.accounts import Accounts + self._accounts = Accounts(self) return self._accounts @property - def api(self): + def api(self) -> "Api": """ Access the Api Twilio Domain :returns: Api Twilio Domain - :rtype: twilio.rest.api.Api """ if self._api is None: from twilio.rest.api import Api + self._api = Api(self) return self._api @property - def chat(self): + 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 + """ + 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 - :rtype: twilio.rest.chat.Chat """ if self._chat is None: from twilio.rest.chat import Chat + self._chat = Chat(self) return self._chat @property - def fax(self): + def content(self) -> "Content": + """ + Access the Content Twilio Domain + + :returns: Content Twilio Domain + """ + 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": + """ + 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 Fax Twilio Domain + Access the Intelligence Twilio Domain - :returns: Fax Twilio Domain - :rtype: twilio.rest.fax.Fax + :returns: Intelligence Twilio Domain """ - if self._fax is None: - from twilio.rest.fax import Fax - self._fax = Fax(self) - return self._fax + if self._intelligence is None: + from twilio.rest.intelligence import Intelligence + + self._intelligence = Intelligence(self) + return self._intelligence @property - def ip_messaging(self): + def ip_messaging(self) -> "IpMessaging": """ Access the IpMessaging Twilio Domain :returns: IpMessaging Twilio Domain - :rtype: twilio.rest.ip_messaging.IpMessaging """ 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): + def lookups(self) -> "Lookups": """ Access the Lookups Twilio Domain :returns: Lookups Twilio Domain - :rtype: twilio.rest.lookups.Lookups """ if self._lookups is None: from twilio.rest.lookups import Lookups + self._lookups = Lookups(self) return self._lookups @property - def monitor(self): + 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 - :rtype: twilio.rest.monitor.Monitor """ if self._monitor is None: from twilio.rest.monitor import Monitor + self._monitor = Monitor(self) return self._monitor @property - def notify(self): + def notify(self) -> "Notify": """ Access the Notify Twilio Domain :returns: Notify Twilio Domain - :rtype: twilio.rest.notify.Notify """ if self._notify is None: from twilio.rest.notify import Notify + self._notify = Notify(self) return self._notify @property - def preview(self): + 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 - :rtype: twilio.rest.preview.Preview """ if self._preview is None: from twilio.rest.preview import Preview + self._preview = Preview(self) return self._preview @property - def pricing(self): + def pricing(self) -> "Pricing": """ Access the Pricing Twilio Domain :returns: Pricing Twilio Domain - :rtype: twilio.rest.pricing.Pricing """ if self._pricing is None: from twilio.rest.pricing import Pricing + self._pricing = Pricing(self) return self._pricing @property - def proxy(self): + def proxy(self) -> "Proxy": """ Access the Proxy Twilio Domain :returns: Proxy Twilio Domain - :rtype: twilio.rest.proxy.Proxy """ if self._proxy is None: from twilio.rest.proxy import Proxy + self._proxy = Proxy(self) return self._proxy @property - def taskrouter(self): + 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 - :rtype: twilio.rest.taskrouter.Taskrouter """ if self._taskrouter is None: from twilio.rest.taskrouter import Taskrouter + self._taskrouter = Taskrouter(self) return self._taskrouter @property - def trunking(self): + def trunking(self) -> "Trunking": """ Access the Trunking Twilio Domain :returns: Trunking Twilio Domain - :rtype: twilio.rest.trunking.Trunking """ if self._trunking is None: from twilio.rest.trunking import Trunking + self._trunking = Trunking(self) return self._trunking @property - def video(self): + 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 - :rtype: twilio.rest.video.Video """ if self._video is None: from twilio.rest.video import Video + self._video = Video(self) return self._video @property - def messaging(self): + def voice(self) -> "Voice": """ - Access the Messaging Twilio Domain + Access the Voice Twilio Domain - :returns: Messaging Twilio Domain - :rtype: twilio.rest.messaging.Messaging + :returns: Voice Twilio Domain """ - if self._messaging is None: - from twilio.rest.messaging import Messaging - self._messaging = Messaging(self) - return self._messaging + if self._voice is None: + from twilio.rest.voice import Voice + + self._voice = Voice(self) + return self._voice @property - def wireless(self): + def wireless(self) -> "Wireless": """ Access the Wireless Twilio Domain :returns: Wireless Twilio Domain - :rtype: twilio.rest.wireless.Wireless """ if self._wireless is None: from twilio.rest.wireless import Wireless + self._wireless = Wireless(self) return self._wireless @property - def sync(self): - """ - Access the Sync Twilio Domain - - :returns: Sync Twilio Domain - :rtype: twilio.rest.sync.Sync - """ - if self._sync is None: - from twilio.rest.sync import Sync - self._sync = Sync(self) - return self._sync - - @property - def studio(self): - """ - Access the Studio Twilio Domain - - :returns: Studio Twilio Domain - :rtype: twilio.rest.studio.Studio - """ - if self._studio is None: - from twilio.rest.studio import Studio - self._studio = Studio(self) - return self._studio - - @property - def addresses(self): - """ - :rtype: twilio.rest.api.v2010.account.address.AddressList - """ + def addresses(self) -> "AddressList": return self.api.account.addresses @property - def applications(self): - """ - :rtype: twilio.rest.api.v2010.account.application.ApplicationList - """ + def applications(self) -> "ApplicationList": return self.api.account.applications @property - def authorized_connect_apps(self): - """ - :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppList - """ + def authorized_connect_apps(self) -> "AuthorizedConnectAppList": return self.api.account.authorized_connect_apps @property - def available_phone_numbers(self): - """ - :rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryList - """ + def available_phone_numbers(self) -> "AvailablePhoneNumberCountryList": return self.api.account.available_phone_numbers @property - def calls(self): - """ - :rtype: twilio.rest.api.v2010.account.call.CallList - """ + def balance(self) -> "BalanceList": + return self.api.account.balance + + @property + def calls(self) -> "CallList": return self.api.account.calls @property - def conferences(self): - """ - :rtype: twilio.rest.api.v2010.account.conference.ConferenceList - """ + def conferences(self) -> "ConferenceList": return self.api.account.conferences @property - def connect_apps(self): - """ - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppList - """ + def connect_apps(self) -> "ConnectAppList": return self.api.account.connect_apps @property - def incoming_phone_numbers(self): - """ - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberList - """ + def incoming_phone_numbers(self) -> "IncomingPhoneNumberList": return self.api.account.incoming_phone_numbers @property - def keys(self): - """ - :rtype: twilio.rest.api.v2010.account.key.KeyList - """ + def keys(self) -> "KeyList": return self.api.account.keys @property - def messages(self): - """ - :rtype: twilio.rest.api.v2010.account.message.MessageList - """ + def new_keys(self) -> "NewKeyList": + return self.api.account.new_keys + + @property + def messages(self) -> "MessageList": return self.api.account.messages @property - def new_keys(self): - """ - :rtype: twilio.rest.api.v2010.account.new_key.NewKeyList - """ - return self.api.account.new_keys + def signing_keys(self) -> "SigningKeyList": + return self.api.account.signing_keys @property - def new_signing_keys(self): - """ - :rtype: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyList - """ + def new_signing_keys(self) -> "NewSigningKeyList": return self.api.account.new_signing_keys @property - def notifications(self): - """ - :rtype: twilio.rest.api.v2010.account.notification.NotificationList - """ + def notifications(self) -> "NotificationList": return self.api.account.notifications @property - def outgoing_caller_ids(self): - """ - :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdList - """ + def outgoing_caller_ids(self) -> "OutgoingCallerIdList": return self.api.account.outgoing_caller_ids @property - def queues(self): - """ - :rtype: twilio.rest.api.v2010.account.queue.QueueList - """ + 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): - """ - :rtype: twilio.rest.api.v2010.account.recording.RecordingList - """ + def recordings(self) -> "RecordingList": return self.api.account.recordings @property - def signing_keys(self): - """ - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyList - """ - return self.api.account.signing_keys + def short_codes(self) -> "ShortCodeList": + return self.api.account.short_codes @property - def sip(self): - """ - :rtype: twilio.rest.api.v2010.account.sip.SipList - """ + def sip(self) -> "SipList": return self.api.account.sip @property - def short_codes(self): - """ - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeList - """ - return self.api.account.short_codes - - @property - def tokens(self): - """ - :rtype: twilio.rest.api.v2010.account.token.TokenList - """ + def tokens(self) -> "TokenList": return self.api.account.tokens @property - def transcriptions(self): - """ - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionList - """ + def transcriptions(self) -> "TranscriptionList": return self.api.account.transcriptions @property - def usage(self): - """ - :rtype: twilio.rest.api.v2010.account.usage.UsageList - """ + def usage(self) -> "UsageList": return self.api.account.usage - - @property - def validation_requests(self): - """ - :rtype: twilio.rest.api.v2010.account.validation_request.ValidationRequestList - """ - return self.api.account.validation_requests - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return ''.format(self.account_sid) - - -@obsolete_client -class TwilioClient(object): - """ Dummy client which provides no functionality. Please use - twilio.rest.Client instead. """ - - def __init__(self, *args): - pass - - -@obsolete_client -class TwilioRestClient(object): - """ Dummy client which provides no functionality. Please use - twilio.rest.Client instead. """ - - def __init__(self, *args): - pass - - -@obsolete_client -class TwilioIpMessagingClient(object): - """ Dummy client which provides no functionality. Please use - twilio.rest.Client instead. """ - - def __init__(self, *args): - pass - - -@obsolete_client -class TwilioLookupsClient(object): - """ Dummy client which provides no functionality. Please use - twilio.rest.Client instead. """ - - def __init__(self, *args): - pass - - -@obsolete_client -class TwilioMonitorClient(object): - """ Dummy client which provides no functionality. Please use - twilio.rest.Client instead. """ - - def __init__(self, *args): - pass - - -@obsolete_client -class TwilioPricingClient(object): - """ Dummy client which provides no functionality. Please use - twilio.rest.Client instead. """ - - def __init__(self, *args): - pass - - -@obsolete_client -class TwilioTaskRouterClient(object): - """ Dummy client which provides no functionality. Please use - twilio.rest.Client instead. """ - - def __init__(self, *args): - pass - - -@obsolete_client -class TwilioTrunkingClient(object): - """ Dummy client which provides no functionality. Please use - twilio.rest.Client instead. """ - - def __init__(self, *args): - pass 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 "" diff --git a/twilio/rest/accounts/__init__.py b/twilio/rest/accounts/__init__.py index a591948725..e2275aea44 100644 --- a/twilio/rest/accounts/__init__.py +++ b/twilio/rest/accounts/__init__.py @@ -1,53 +1,35 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" +from warnings import warn -from twilio.base.domain import Domain -from twilio.rest.accounts.v1 import V1 +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(Domain): - - def __init__(self, twilio): - """ - Initialize the Accounts Domain - - :returns: Domain for Accounts - :rtype: twilio.rest.accounts.Accounts - """ - super(Accounts, self).__init__(twilio) - - self.base_url = 'https://accounts.twilio.com' - - # Versions - self._v1 = None - +class Accounts(AccountsBase): @property - def v1(self): - """ - :returns: Version v1 of accounts - :rtype: twilio.rest.accounts.v1.V1 - """ - if self._v1 is None: - self._v1 = V1(self) - return self._v1 + 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): - """ - :rtype: twilio.rest.accounts.v1.credential.CredentialList - """ + def credentials(self) -> CredentialList: + warn( + "credentials is deprecated. Use v1.credentials instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v1.credentials - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' + @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 index 3841d1599d..6f5012d0fa 100644 --- a/twilio/rest/accounts/v1/__init__.py +++ b/twilio/rest/accounts/v1/__init__.py @@ -1,42 +1,83 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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): + def __init__(self, domain: Domain): """ Initialize the V1 version of Accounts - :returns: V1 version of Accounts - :rtype: twilio.rest.accounts.v1.V1.V1 + :param domain: The Twilio.accounts domain """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._credentials = None + 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 credentials(self): - """ - :rtype: twilio.rest.accounts.v1.credential.CredentialList - """ + 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 - def __repr__(self): + @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 - :rtype: str """ - return '' + return "" 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 "" + + +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 "" + + +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 "" 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 "" + + +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 "" 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 "" + + +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 "" diff --git a/twilio/rest/accounts/v1/credential/__init__.py b/twilio/rest/accounts/v1/credential/__init__.py index 9eb299de1c..e9c4653f0c 100644 --- a/twilio/rest/accounts/v1/credential/__init__.py +++ b/twilio/rest/accounts/v1/credential/__init__.py @@ -1,133 +1,65 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base.instance_resource import InstanceResource +from typing import Optional + + from twilio.base.list_resource import ListResource -from twilio.base.page import Page +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): + def __init__(self, version: Version): """ Initialize the CredentialList - :param Version version: Version that contains the resource + :param version: Version that contains the resource - :returns: twilio.rest.accounts.v1.credential.CredentialList - :rtype: twilio.rest.accounts.v1.credential.CredentialList """ - super(CredentialList, self).__init__(version) - - # Path Solution - self._solution = {} - - # Components - self._public_key = None - self._aws = None + super().__init__(version) - @property - def public_key(self): - """ - Access the public_key + self._uri = "/Credentials" - :returns: twilio.rest.accounts.v1.credential.public_key.PublicKeyList - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyList - """ - if self._public_key is None: - self._public_key = PublicKeyList(self._version, ) - return self._public_key + self._aws: Optional[AwsList] = None + self._public_key: Optional[PublicKeyList] = None @property - def aws(self): + def aws(self) -> AwsList: """ Access the aws - - :returns: twilio.rest.accounts.v1.credential.aws.AwsList - :rtype: twilio.rest.accounts.v1.credential.aws.AwsList """ if self._aws is None: - self._aws = AwsList(self._version, ) + self._aws = AwsList(self._version) return self._aws - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class CredentialPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the CredentialPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.accounts.v1.credential.CredentialPage - :rtype: twilio.rest.accounts.v1.credential.CredentialPage - """ - super(CredentialPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of CredentialInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.accounts.v1.credential.CredentialInstance - :rtype: twilio.rest.accounts.v1.credential.CredentialInstance - """ - return CredentialInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class CredentialInstance(InstanceResource): - """ """ - - def __init__(self, version, payload): + @property + def public_key(self) -> PublicKeyList: """ - Initialize the CredentialInstance - - :returns: twilio.rest.accounts.v1.credential.CredentialInstance - :rtype: twilio.rest.accounts.v1.credential.CredentialInstance + Access the public_key """ - super(CredentialInstance, self).__init__(version) - - # Context - self._context = None - self._solution = {} + if self._public_key is None: + self._public_key = PublicKeyList(self._version) + return self._public_key - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/accounts/v1/credential/aws.py b/twilio/rest/accounts/v1/credential/aws.py index 58d71f5538..ba5335accd 100644 --- a/twilio/rest/accounts/v1/credential/aws.py +++ b/twilio/rest/accounts/v1/credential/aws.py @@ -1,412 +1,609 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 AwsList(ListResource): - """ """ +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 - def __init__(self, version): + @property + def _proxy(self) -> "AwsContext": """ - Initialize the AwsList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource + :returns: AwsContext for this AwsInstance + """ + if self._context is None: + self._context = AwsContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.accounts.v1.credential.aws.AwsList - :rtype: twilio.rest.accounts.v1.credential.aws.AwsList + def delete(self) -> bool: """ - super(AwsList, self).__init__(version) + Deletes the AwsInstance - # Path Solution - self._solution = {} - self._uri = '/Credentials/AWS'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.accounts.v1.credential.aws.AwsInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the AwsInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the AwsInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.accounts.v1.credential.aws.AwsInstance] + :returns: The fetched AwsInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_async(self) -> "AwsInstance": """ - Retrieve a single page of AwsInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the AwsInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of AwsInstance - :rtype: twilio.rest.accounts.v1.credential.aws.AwsPage + :returns: The fetched AwsInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return AwsPage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def get_page(self, target_url): + def update(self, friendly_name: Union[str, object] = values.unset) -> "AwsInstance": """ - Retrieve a specific page of AwsInstance records from the API. - Request is executed immediately + Update the AwsInstance - :param str target_url: API-generated URL for the requested results page + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: Page of AwsInstance - :rtype: twilio.rest.accounts.v1.credential.aws.AwsPage + :returns: The updated AwsInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + friendly_name=friendly_name, ) - return AwsPage(self._version, response, self._solution) - - def create(self, credentials, friendly_name=values.unset, - account_sid=values.unset): + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "AwsInstance": """ - Create a new AwsInstance + Asynchronous coroutine to update the AwsInstance - :param unicode credentials: The credentials - :param unicode friendly_name: The friendly_name - :param unicode account_sid: The account_sid + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: Newly created AwsInstance - :rtype: twilio.rest.accounts.v1.credential.aws.AwsInstance + :returns: The updated AwsInstance """ - data = values.of({ - 'Credentials': credentials, - 'FriendlyName': friendly_name, - 'AccountSid': account_sid, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, + return await self._proxy.update_async( + friendly_name=friendly_name, ) - return AwsInstance(self._version, payload, ) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a AwsContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param sid: The sid - :returns: twilio.rest.accounts.v1.credential.aws.AwsContext - :rtype: twilio.rest.accounts.v1.credential.aws.AwsContext +class AwsContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - return AwsContext(self._version, sid=sid, ) + Initialize the AwsContext - def __call__(self, sid): + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the AWS resource to update. """ - Constructs a AwsContext + super().__init__(version) - :param sid: The sid + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/AWS/{sid}".format(**self._solution) - :returns: twilio.rest.accounts.v1.credential.aws.AwsContext - :rtype: twilio.rest.accounts.v1.credential.aws.AwsContext + def delete(self) -> bool: """ - return AwsContext(self._version, sid=sid, ) + Deletes the AwsInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class AwsPage(Page): - """ """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, response, solution): + async def delete_async(self) -> bool: """ - Initialize the AwsPage + Asynchronous coroutine that deletes the AwsInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.accounts.v1.credential.aws.AwsPage - :rtype: twilio.rest.accounts.v1.credential.aws.AwsPage + :returns: True if delete succeeds, False otherwise """ - super(AwsPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AwsInstance: """ - Build an instance of AwsInstance + Fetch the AwsInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.accounts.v1.credential.aws.AwsInstance - :rtype: twilio.rest.accounts.v1.credential.aws.AwsInstance + :returns: The fetched AwsInstance """ - return AwsInstance(self._version, payload, ) - def __repr__(self): - """ - Provide a friendly representation + headers = values.of({}) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Accept"] = "application/json" + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) -class AwsContext(InstanceContext): - """ """ + return AwsInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __init__(self, version, sid): + async def fetch_async(self) -> AwsInstance: """ - Initialize the AwsContext + Asynchronous coroutine to fetch the AwsInstance - :param Version version: Version that contains the resource - :param sid: The sid - :returns: twilio.rest.accounts.v1.credential.aws.AwsContext - :rtype: twilio.rest.accounts.v1.credential.aws.AwsContext + :returns: The fetched AwsInstance """ - super(AwsContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Credentials/AWS/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - def fetch(self): + 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: """ - Fetch a 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: Fetched AwsInstance - :rtype: twilio.rest.accounts.v1.credential.aws.AwsInstance + :returns: The updated AwsInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + data = values.of( + { + "FriendlyName": friendly_name, + } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - return AwsInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" - def update(self, friendly_name=values.unset): + 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: """ - Update the AwsInstance + Asynchronous coroutine to update the AwsInstance - :param unicode friendly_name: The friendly_name + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: Updated AwsInstance - :rtype: twilio.rest.accounts.v1.credential.aws.AwsInstance + :returns: The updated AwsInstance """ - data = values.of({'FriendlyName': friendly_name, }) - payload = self._version.update( - 'POST', - self._uri, - data=data, + data = values.of( + { + "FriendlyName": friendly_name, + } ) + headers = values.of({}) - return AwsInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def delete(self): + 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: """ - Deletes the AwsInstance + Provide a friendly representation - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".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 self._version.delete('delete', self._uri) + return AwsInstance(self._version, payload) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" -class AwsInstance(InstanceResource): - """ """ +class AwsList(ListResource): - def __init__(self, version, payload, sid=None): + def __init__(self, version: Version): """ - Initialize the AwsInstance + Initialize the AwsList + + :param version: Version that contains the resource - :returns: twilio.rest.accounts.v1.credential.aws.AwsInstance - :rtype: twilio.rest.accounts.v1.credential.aws.AwsInstance """ - super(AwsInstance, self).__init__(version) + super().__init__(version) - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'friendly_name': payload['friendly_name'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - } + 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 - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + :param credentials: A string that contains the AWS access credentials in the format `:`. 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. - @property - def _proxy(self): + :returns: The created AwsInstance """ - 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 - :rtype: twilio.rest.accounts.v1.credential.aws.AwsContext + 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: """ - if self._context is None: - self._context = AwsContext(self._version, sid=self._solution['sid'], ) - return self._context + Asynchronously create the AwsInstance - @property - def sid(self): + :param credentials: A string that contains the AWS access credentials in the format `:`. 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 """ - :returns: The sid - :rtype: unicode + + 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]: """ - return self._properties['sid'] + 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. - @property - def account_sid(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The account_sid - :rtype: unicode + 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]: """ - return self._properties['account_sid'] + 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. - @property - def friendly_name(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The friendly_name - :rtype: unicode + 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]: """ - return self._properties['friendly_name'] + Lists AwsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def date_created(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The date_created - :rtype: datetime + 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]: """ - return self._properties['date_created'] + 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. - @property - def date_updated(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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: """ - :returns: The date_updated - :rtype: datetime + 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 """ - return self._properties['date_updated'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def url(self): + headers = values.of({"Content-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 """ - :returns: The url - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of AwsInstance """ - Fetch a AwsInstance + response = self._version.domain.twilio.request("GET", target_url) + return AwsPage(self._version, response) - :returns: Fetched AwsInstance - :rtype: twilio.rest.accounts.v1.credential.aws.AwsInstance + async def get_page_async(self, target_url: str) -> AwsPage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of AwsInstance records from the API. + Request is executed immediately - def update(self, friendly_name=values.unset): + :param target_url: API-generated URL for the requested results page + + :returns: Page of AwsInstance """ - Update the AwsInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return AwsPage(self._version, response) - :param unicode friendly_name: The friendly_name + def get(self, sid: str) -> AwsContext: + """ + Constructs a AwsContext - :returns: Updated AwsInstance - :rtype: twilio.rest.accounts.v1.credential.aws.AwsInstance + :param sid: The Twilio-provided string that uniquely identifies the AWS resource to update. """ - return self._proxy.update(friendly_name=friendly_name, ) + return AwsContext(self._version, sid=sid) - def delete(self): + def __call__(self, sid: str) -> AwsContext: """ - Deletes the AwsInstance + Constructs a AwsContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the AWS resource to update. """ - return self._proxy.delete() + return AwsContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/accounts/v1/credential/public_key.py b/twilio/rest/accounts/v1/credential/public_key.py index c3fcf959b8..c2b4f9bbee 100644 --- a/twilio/rest/accounts/v1/credential/public_key.py +++ b/twilio/rest/accounts/v1/credential/public_key.py @@ -1,412 +1,613 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 PublicKeyList(ListResource): - """ """ +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 - def __init__(self, version): + @property + def _proxy(self) -> "PublicKeyContext": """ - Initialize the PublicKeyList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource + :returns: PublicKeyContext for this PublicKeyInstance + """ + if self._context is None: + self._context = PublicKeyContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.accounts.v1.credential.public_key.PublicKeyList - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyList + def delete(self) -> bool: """ - super(PublicKeyList, self).__init__(version) + Deletes the PublicKeyInstance - # Path Solution - self._solution = {} - self._uri = '/Credentials/PublicKeys'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.accounts.v1.credential.public_key.PublicKeyInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the PublicKeyInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the PublicKeyInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.accounts.v1.credential.public_key.PublicKeyInstance] + :returns: The fetched PublicKeyInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_async(self) -> "PublicKeyInstance": """ - Retrieve a single page of PublicKeyInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the PublicKeyInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of PublicKeyInstance - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyPage + :returns: The fetched PublicKeyInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return PublicKeyPage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def get_page(self, target_url): + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> "PublicKeyInstance": """ - Retrieve a specific page of PublicKeyInstance records from the API. - Request is executed immediately + Update the PublicKeyInstance - :param str target_url: API-generated URL for the requested results page + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: Page of PublicKeyInstance - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyPage + :returns: The updated PublicKeyInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + friendly_name=friendly_name, ) - return PublicKeyPage(self._version, response, self._solution) - - def create(self, public_key, friendly_name=values.unset, - account_sid=values.unset): + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "PublicKeyInstance": """ - Create a new PublicKeyInstance + Asynchronous coroutine to update the PublicKeyInstance - :param unicode public_key: URL encoded representation of the public key - :param unicode friendly_name: A human readable description of this resource - :param unicode account_sid: The Subaccount this Credential should be associated with. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: Newly created PublicKeyInstance - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyInstance + :returns: The updated PublicKeyInstance """ - data = values.of({ - 'PublicKey': public_key, - 'FriendlyName': friendly_name, - 'AccountSid': account_sid, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, + return await self._proxy.update_async( + friendly_name=friendly_name, ) - return PublicKeyInstance(self._version, payload, ) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a PublicKeyContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param sid: Fetch by unique Credential Sid - :returns: twilio.rest.accounts.v1.credential.public_key.PublicKeyContext - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyContext +class PublicKeyContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - return PublicKeyContext(self._version, sid=sid, ) + Initialize the PublicKeyContext - def __call__(self, sid): + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the PublicKey resource to update. """ - Constructs a PublicKeyContext + super().__init__(version) - :param sid: Fetch by unique Credential Sid + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/PublicKeys/{sid}".format(**self._solution) - :returns: twilio.rest.accounts.v1.credential.public_key.PublicKeyContext - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyContext + def delete(self) -> bool: """ - return PublicKeyContext(self._version, sid=sid, ) + Deletes the PublicKeyInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class PublicKeyPage(Page): - """ """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, response, solution): + async def delete_async(self) -> bool: """ - Initialize the PublicKeyPage + Asynchronous coroutine that deletes the PublicKeyInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.accounts.v1.credential.public_key.PublicKeyPage - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyPage + :returns: True if delete succeeds, False otherwise """ - super(PublicKeyPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> PublicKeyInstance: """ - Build an instance of PublicKeyInstance + Fetch the PublicKeyInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.accounts.v1.credential.public_key.PublicKeyInstance - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyInstance + :returns: The fetched PublicKeyInstance """ - return PublicKeyInstance(self._version, payload, ) - def __repr__(self): - """ - Provide a friendly representation + headers = values.of({}) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Accept"] = "application/json" + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) -class PublicKeyContext(InstanceContext): - """ """ + return PublicKeyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __init__(self, version, sid): + async def fetch_async(self) -> PublicKeyInstance: """ - Initialize the PublicKeyContext + Asynchronous coroutine to fetch the PublicKeyInstance - :param Version version: Version that contains the resource - :param sid: Fetch by unique Credential Sid - :returns: twilio.rest.accounts.v1.credential.public_key.PublicKeyContext - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyContext + :returns: The fetched PublicKeyInstance """ - super(PublicKeyContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Credentials/PublicKeys/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - def fetch(self): + 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: """ - Fetch a 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: Fetched PublicKeyInstance - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyInstance + :returns: The updated PublicKeyInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + data = values.of( + { + "FriendlyName": friendly_name, + } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - return PublicKeyInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" - def update(self, friendly_name=values.unset): + 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: """ - Update the PublicKeyInstance + Asynchronous coroutine to update the PublicKeyInstance - :param unicode friendly_name: A human readable description of this resource + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: Updated PublicKeyInstance - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyInstance + :returns: The updated PublicKeyInstance """ - data = values.of({'FriendlyName': friendly_name, }) - payload = self._version.update( - 'POST', - self._uri, - data=data, + data = values.of( + { + "FriendlyName": friendly_name, + } ) + headers = values.of({}) - return PublicKeyInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def delete(self): + 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: """ - Deletes the PublicKeyInstance + Provide a friendly representation - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".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 self._version.delete('delete', self._uri) + return PublicKeyInstance(self._version, payload) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" -class PublicKeyInstance(InstanceResource): - """ """ +class PublicKeyList(ListResource): - def __init__(self, version, payload, sid=None): + def __init__(self, version: Version): """ - Initialize the PublicKeyInstance + Initialize the PublicKeyList + + :param version: Version that contains the resource - :returns: twilio.rest.accounts.v1.credential.public_key.PublicKeyInstance - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyInstance """ - super(PublicKeyInstance, self).__init__(version) + super().__init__(version) - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'friendly_name': payload['friendly_name'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - } + 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 - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + :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 - @property - def _proxy(self): + :returns: The created PublicKeyInstance """ - 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 - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyContext + 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: """ - if self._context is None: - self._context = PublicKeyContext(self._version, sid=self._solution['sid'], ) - return self._context + Asynchronously create the PublicKeyInstance - @property - def sid(self): + :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 """ - :returns: A 34 character string that uniquely identifies this resource. - :rtype: unicode + + 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]: """ - return self._properties['sid'] + 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. - @property - def account_sid(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: AccountSid the Credential resource belongs to - :rtype: unicode + 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]: """ - return self._properties['account_sid'] + 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. - @property - def friendly_name(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: A human readable description of this resource - :rtype: unicode + 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]: """ - return self._properties['friendly_name'] + Lists PublicKeyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def date_created(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The date this resource was created - :rtype: datetime + 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]: """ - return self._properties['date_created'] + 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. - @property - def date_updated(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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: """ - :returns: The date this resource was last updated - :rtype: datetime + 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 """ - return self._properties['date_updated'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def url(self): + headers = values.of({"Content-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 """ - :returns: The URI for this resource, relative to `https://accounts.twilio.com` - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of PublicKeyInstance """ - Fetch a PublicKeyInstance + response = self._version.domain.twilio.request("GET", target_url) + return PublicKeyPage(self._version, response) - :returns: Fetched PublicKeyInstance - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyInstance + async def get_page_async(self, target_url: str) -> PublicKeyPage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of PublicKeyInstance records from the API. + Request is executed immediately - def update(self, friendly_name=values.unset): + :param target_url: API-generated URL for the requested results page + + :returns: Page of PublicKeyInstance """ - Update the PublicKeyInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return PublicKeyPage(self._version, response) - :param unicode friendly_name: A human readable description of this resource + def get(self, sid: str) -> PublicKeyContext: + """ + Constructs a PublicKeyContext - :returns: Updated PublicKeyInstance - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyInstance + :param sid: The Twilio-provided string that uniquely identifies the PublicKey resource to update. """ - return self._proxy.update(friendly_name=friendly_name, ) + return PublicKeyContext(self._version, sid=sid) - def delete(self): + def __call__(self, sid: str) -> PublicKeyContext: """ - Deletes the PublicKeyInstance + Constructs a PublicKeyContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the PublicKey resource to update. """ - return self._proxy.delete() + return PublicKeyContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 "" + + +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 "" 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 "" + + +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 "" + + +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 "" 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 "" diff --git a/twilio/rest/api/__init__.py b/twilio/rest/api/__init__.py index c14010d4ab..08d5885cbd 100644 --- a/twilio/rest/api/__init__.py +++ b/twilio/rest/api/__init__.py @@ -1,222 +1,258 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base.domain import Domain -from twilio.rest.api.v2010 import V2010 - - -class Api(Domain): - - def __init__(self, twilio): - """ - Initialize the Api Domain - - :returns: Domain for Api - :rtype: twilio.rest.api.Api - """ - super(Api, self).__init__(twilio) - - self.base_url = 'https://api.twilio.com' - - # Versions - self._v2010 = None - - @property - def v2010(self): - """ - :returns: Version v2010 of api - :rtype: twilio.rest.api.v2010.V2010 - """ - if self._v2010 is None: - self._v2010 = V2010(self) - return self._v2010 - +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): - """ - :returns: Account provided as the authenticating account - :rtype: twilio.rest.api.v2010.account.AccountContext - """ + def account(self) -> AccountContext: return self.v2010.account @property - def accounts(self): - """ - :rtype: twilio.rest.api.v2010.account.AccountList - """ + def accounts(self) -> AccountList: return self.v2010.accounts @property - def addresses(self): - """ - :rtype: twilio.rest.api.v2010.account.address.AddressList - """ + def addresses(self) -> AddressList: + warn( + "addresses is deprecated. Use account.addresses instead.", + DeprecationWarning, + stacklevel=2, + ) return self.account.addresses @property - def applications(self): - """ - :rtype: twilio.rest.api.v2010.account.application.ApplicationList - """ + 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): - """ - :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppList - """ + 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): - """ - :rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryList - """ + 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 calls(self): - """ - :rtype: twilio.rest.api.v2010.account.call.CallList - """ + 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): - """ - :rtype: twilio.rest.api.v2010.account.conference.ConferenceList - """ + def conferences(self) -> ConferenceList: + warn( + "conferences is deprecated. Use account.conferences instead.", + DeprecationWarning, + stacklevel=2, + ) return self.account.conferences @property - def connect_apps(self): - """ - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppList - """ + 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): - """ - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberList - """ + 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): - """ - :rtype: twilio.rest.api.v2010.account.key.KeyList - """ + def keys(self) -> KeyList: + warn( + "keys is deprecated. Use account.keys instead.", + DeprecationWarning, + stacklevel=2, + ) return self.account.keys @property - def messages(self): - """ - :rtype: twilio.rest.api.v2010.account.message.MessageList - """ + def messages(self) -> MessageList: + warn( + "messages is deprecated. Use account.messages instead.", + DeprecationWarning, + stacklevel=2, + ) return self.account.messages @property - def new_keys(self): - """ - :rtype: twilio.rest.api.v2010.account.new_key.NewKeyList - """ + 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): - """ - :rtype: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyList - """ + 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): - """ - :rtype: twilio.rest.api.v2010.account.notification.NotificationList - """ + 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): - """ - :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdList - """ + 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): - """ - :rtype: twilio.rest.api.v2010.account.queue.QueueList - """ + def queues(self) -> QueueList: + warn( + "queues is deprecated. Use account.queues instead.", + DeprecationWarning, + stacklevel=2, + ) return self.account.queues @property - def recordings(self): - """ - :rtype: twilio.rest.api.v2010.account.recording.RecordingList - """ + def recordings(self) -> RecordingList: + warn( + "recordings is deprecated. Use account.recordings instead.", + DeprecationWarning, + stacklevel=2, + ) return self.account.recordings @property - def signing_keys(self): - """ - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyList - """ + 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): - """ - :rtype: twilio.rest.api.v2010.account.sip.SipList - """ + def sip(self) -> SipList: + warn( + "sip is deprecated. Use account.sip instead.", + DeprecationWarning, + stacklevel=2, + ) return self.account.sip @property - def short_codes(self): - """ - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeList - """ + 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): - """ - :rtype: twilio.rest.api.v2010.account.token.TokenList - """ + def tokens(self) -> TokenList: + warn( + "tokens is deprecated. Use account.tokens instead.", + DeprecationWarning, + stacklevel=2, + ) return self.account.tokens @property - def transcriptions(self): - """ - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionList - """ + def transcriptions(self) -> TranscriptionList: + warn( + "transcriptions is deprecated. Use account.transcriptions instead.", + DeprecationWarning, + stacklevel=2, + ) return self.account.transcriptions @property - def usage(self): - """ - :rtype: twilio.rest.api.v2010.account.usage.UsageList - """ + def usage(self) -> UsageList: + warn( + "usage is deprecated. Use account.usage instead.", + DeprecationWarning, + stacklevel=2, + ) return self.account.usage @property - def validation_requests(self): - """ - :rtype: twilio.rest.api.v2010.account.validation_request.ValidationRequestList - """ + def validation_requests(self) -> ValidationRequestList: + warn( + "validation_requests is deprecated. Use account.validation_requests instead.", + DeprecationWarning, + stacklevel=2, + ) return self.account.validation_requests - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/api/v2010/__init__.py b/twilio/rest/api/v2010/__init__.py index 49aa728493..2efb4ff3d0 100644 --- a/twilio/rest/api/v2010/__init__.py +++ b/twilio/rest/api/v2010/__init__.py @@ -1,224 +1,59 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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.rest.api.v2010.account import AccountContext +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): + def __init__(self, domain: Domain): """ Initialize the V2010 version of Api - :returns: V2010 version of Api - :rtype: twilio.rest.api.v2010.V2010.V2010 + :param domain: The Twilio.api domain """ - super(V2010, self).__init__(domain) - self.version = '2010-04-01' - self._accounts = None - self._account = None + super().__init__(domain, "2010-04-01") + self._accounts: Optional[AccountList] = None + self._account: Optional[AccountContext] = None @property - def accounts(self): - """ - :rtype: twilio.rest.api.v2010.account.AccountList - """ + def accounts(self) -> AccountList: if self._accounts is None: self._accounts = AccountList(self) return self._accounts @property - def account(self): - """ - :returns: Account provided as the authenticating account - :rtype: AccountContext - """ + 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): + def account(self, value: AccountContext) -> None: """ - Setter to override the primary account - - :param AccountContext|AccountInstance value: account to use as primary account + Setter to override account + :param value: value to use as account """ self._account = value - @property - def addresses(self): - """ - :rtype: twilio.rest.api.v2010.account.address.AddressList - """ - return self.account.addresses - - @property - def applications(self): - """ - :rtype: twilio.rest.api.v2010.account.application.ApplicationList - """ - return self.account.applications - - @property - def authorized_connect_apps(self): - """ - :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppList - """ - return self.account.authorized_connect_apps - - @property - def available_phone_numbers(self): - """ - :rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryList - """ - return self.account.available_phone_numbers - - @property - def calls(self): - """ - :rtype: twilio.rest.api.v2010.account.call.CallList - """ - return self.account.calls - - @property - def conferences(self): - """ - :rtype: twilio.rest.api.v2010.account.conference.ConferenceList - """ - return self.account.conferences - - @property - def connect_apps(self): - """ - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppList - """ - return self.account.connect_apps - - @property - def incoming_phone_numbers(self): - """ - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberList - """ - return self.account.incoming_phone_numbers - - @property - def keys(self): - """ - :rtype: twilio.rest.api.v2010.account.key.KeyList - """ - return self.account.keys - - @property - def messages(self): - """ - :rtype: twilio.rest.api.v2010.account.message.MessageList - """ - return self.account.messages - - @property - def new_keys(self): - """ - :rtype: twilio.rest.api.v2010.account.new_key.NewKeyList - """ - return self.account.new_keys - - @property - def new_signing_keys(self): - """ - :rtype: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyList - """ - return self.account.new_signing_keys - - @property - def notifications(self): - """ - :rtype: twilio.rest.api.v2010.account.notification.NotificationList - """ - return self.account.notifications - - @property - def outgoing_caller_ids(self): - """ - :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdList - """ - return self.account.outgoing_caller_ids - - @property - def queues(self): - """ - :rtype: twilio.rest.api.v2010.account.queue.QueueList - """ - return self.account.queues - - @property - def recordings(self): - """ - :rtype: twilio.rest.api.v2010.account.recording.RecordingList - """ - return self.account.recordings - - @property - def signing_keys(self): - """ - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyList - """ - return self.account.signing_keys - - @property - def sip(self): - """ - :rtype: twilio.rest.api.v2010.account.sip.SipList - """ - return self.account.sip - - @property - def short_codes(self): - """ - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeList - """ - return self.account.short_codes - - @property - def tokens(self): - """ - :rtype: twilio.rest.api.v2010.account.token.TokenList - """ - return self.account.tokens - - @property - def transcriptions(self): - """ - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionList - """ - return self.account.transcriptions - - @property - def usage(self): - """ - :rtype: twilio.rest.api.v2010.account.usage.UsageList - """ - return self.account.usage - - @property - def validation_requests(self): - """ - :rtype: twilio.rest.api.v2010.account.validation_request.ValidationRequestList - """ - return self.account.validation_requests - - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/api/v2010/account/__init__.py b/twilio/rest/api/v2010/account/__init__.py index abe989194e..7c7e2c1069 100644 --- a/twilio/rest/api/v2010/account/__init__.py +++ b/twilio/rest/api/v2010/account/__init__.py @@ -1,21 +1,34 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 import AvailablePhoneNumberCountryList +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 @@ -37,981 +50,1087 @@ from twilio.rest.api.v2010.account.validation_request import ValidationRequestList -class AccountList(ListResource): - """ """ +class AccountInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the AccountList + class Status(object): + ACTIVE = "active" + SUSPENDED = "suspended" + CLOSED = "closed" - :param Version version: Version that contains the resource + class Type(object): + TRIAL = "Trial" + FULL = "Full" - :returns: twilio.rest.api.v2010.account.AccountList - :rtype: twilio.rest.api.v2010.account.AccountList - """ - super(AccountList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {} - self._uri = '/Accounts.json'.format(**self._solution) + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[AccountContext] = None - def create(self, friendly_name=values.unset): + @property + def _proxy(self) -> "AccountContext": """ - Create a new AccountInstance - - :param unicode friendly_name: A human readable description of the account + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: Newly created AccountInstance - :rtype: twilio.rest.api.v2010.account.AccountInstance + :returns: AccountContext for this AccountInstance """ - data = values.of({'FriendlyName': friendly_name, }) + if self._context is None: + self._context = AccountContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + def fetch(self) -> "AccountInstance": + """ + Fetch the AccountInstance - return AccountInstance(self._version, payload, ) - def stream(self, friendly_name=values.unset, status=values.unset, limit=None, - page_size=None): + :returns: The fetched 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 unicode friendly_name: FriendlyName to filter on - :param AccountInstance.Status status: Status to filter on - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return self._proxy.fetch() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.AccountInstance] + async def fetch_async(self) -> "AccountInstance": """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine to fetch the AccountInstance - page = self.page(friendly_name=friendly_name, status=status, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched AccountInstance + """ + return await self._proxy.fetch_async() - def list(self, friendly_name=values.unset, status=values.unset, limit=None, - page_size=None): + def update( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> "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. + Update the AccountInstance - :param unicode friendly_name: FriendlyName to filter on - :param AccountInstance.Status status: Status to filter on - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + :param friendly_name: Update the human-readable description of this Account + :param status: - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.AccountInstance] + :returns: The updated AccountInstance """ - return list(self.stream( + return self._proxy.update( friendly_name=friendly_name, status=status, - limit=limit, - page_size=page_size, - )) + ) - def page(self, friendly_name=values.unset, status=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> "AccountInstance": """ - Retrieve a single page of AccountInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the AccountInstance - :param unicode friendly_name: FriendlyName to filter on - :param AccountInstance.Status status: Status to filter on - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :param friendly_name: Update the human-readable description of this Account + :param status: - :returns: Page of AccountInstance - :rtype: twilio.rest.api.v2010.account.AccountPage + :returns: The updated AccountInstance """ - params = values.of({ - 'FriendlyName': friendly_name, - 'Status': status, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + return await self._proxy.update_async( + friendly_name=friendly_name, + status=status, ) - return AccountPage(self._version, response, self._solution) + @property + def addresses(self) -> AddressList: + """ + Access the addresses + """ + return self._proxy.addresses - def get_page(self, target_url): + @property + def applications(self) -> ApplicationList: """ - Retrieve a specific page of AccountInstance records from the API. - Request is executed immediately + Access the applications + """ + return self._proxy.applications - :param str target_url: API-generated URL for the requested results page + @property + def authorized_connect_apps(self) -> AuthorizedConnectAppList: + """ + Access the authorized_connect_apps + """ + return self._proxy.authorized_connect_apps - :returns: Page of AccountInstance - :rtype: twilio.rest.api.v2010.account.AccountPage + @property + def available_phone_numbers(self) -> AvailablePhoneNumberCountryList: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Access the available_phone_numbers + """ + return self._proxy.available_phone_numbers - return AccountPage(self._version, response, self._solution) + @property + def balance(self) -> BalanceList: + """ + Access the balance + """ + return self._proxy.balance - def get(self, sid): + @property + def calls(self) -> CallList: """ - Constructs a AccountContext + Access the calls + """ + return self._proxy.calls - :param sid: Fetch by unique Account Sid + @property + def conferences(self) -> ConferenceList: + """ + Access the conferences + """ + return self._proxy.conferences - :returns: twilio.rest.api.v2010.account.AccountContext - :rtype: twilio.rest.api.v2010.account.AccountContext + @property + def connect_apps(self) -> ConnectAppList: """ - return AccountContext(self._version, sid=sid, ) + Access the connect_apps + """ + return self._proxy.connect_apps - def __call__(self, sid): + @property + def incoming_phone_numbers(self) -> IncomingPhoneNumberList: """ - Constructs a AccountContext + Access the incoming_phone_numbers + """ + return self._proxy.incoming_phone_numbers - :param sid: Fetch by unique Account Sid + @property + def keys(self) -> KeyList: + """ + Access the keys + """ + return self._proxy.keys - :returns: twilio.rest.api.v2010.account.AccountContext - :rtype: twilio.rest.api.v2010.account.AccountContext + @property + def messages(self) -> MessageList: + """ + Access the messages """ - return AccountContext(self._version, sid=sid, ) + return self._proxy.messages - def __repr__(self): + @property + def new_keys(self) -> NewKeyList: """ - Provide a friendly representation + Access the new_keys + """ + return self._proxy.new_keys - :returns: Machine friendly representation - :rtype: str + @property + def new_signing_keys(self) -> NewSigningKeyList: + """ + Access the new_signing_keys """ - return '' + return self._proxy.new_signing_keys + @property + def notifications(self) -> NotificationList: + """ + Access the notifications + """ + return self._proxy.notifications -class AccountPage(Page): - """ """ + @property + def outgoing_caller_ids(self) -> OutgoingCallerIdList: + """ + Access the outgoing_caller_ids + """ + return self._proxy.outgoing_caller_ids - def __init__(self, version, response, solution): + @property + def queues(self) -> QueueList: + """ + Access the queues """ - Initialize the AccountPage + return self._proxy.queues - :param Version version: Version that contains the resource - :param Response response: Response from the API + @property + def recordings(self) -> RecordingList: + """ + Access the recordings + """ + return self._proxy.recordings - :returns: twilio.rest.api.v2010.account.AccountPage - :rtype: twilio.rest.api.v2010.account.AccountPage + @property + def short_codes(self) -> ShortCodeList: + """ + Access the short_codes """ - super(AccountPage, self).__init__(version, response) + return self._proxy.short_codes - # Path Solution - self._solution = solution + @property + def signing_keys(self) -> SigningKeyList: + """ + Access the signing_keys + """ + return self._proxy.signing_keys - def get_instance(self, payload): + @property + def sip(self) -> SipList: """ - Build an instance of AccountInstance + Access the sip + """ + return self._proxy.sip + + @property + def tokens(self) -> TokenList: + """ + Access the tokens + """ + return self._proxy.tokens - :param dict payload: Payload response from the API + @property + def transcriptions(self) -> TranscriptionList: + """ + Access the transcriptions + """ + return self._proxy.transcriptions + + @property + def usage(self) -> UsageList: + """ + Access the usage + """ + return self._proxy.usage - :returns: twilio.rest.api.v2010.account.AccountInstance - :rtype: twilio.rest.api.v2010.account.AccountInstance + @property + def validation_requests(self) -> ValidationRequestList: + """ + Access the validation_requests """ - return AccountInstance(self._version, payload, ) + return self._proxy.validation_requests - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) class AccountContext(InstanceContext): - """ """ - def __init__(self, version, sid): + def __init__(self, version: Version, sid: str): """ Initialize the AccountContext - :param Version version: Version that contains the resource - :param sid: Fetch by unique Account Sid - - :returns: twilio.rest.api.v2010.account.AccountContext - :rtype: twilio.rest.api.v2010.account.AccountContext + :param version: Version that contains the resource + :param sid: The Account Sid that uniquely identifies the account to update """ - super(AccountContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Accounts/{sid}.json'.format(**self._solution) - - # Dependents - self._addresses = None - self._applications = None - self._authorized_connect_apps = None - self._available_phone_numbers = None - self._calls = None - self._conferences = None - self._connect_apps = None - self._incoming_phone_numbers = None - self._keys = None - self._messages = None - self._new_keys = None - self._new_signing_keys = None - self._notifications = None - self._outgoing_caller_ids = None - self._queues = None - self._recordings = None - self._signing_keys = None - self._sip = None - self._short_codes = None - self._tokens = None - self._transcriptions = None - self._usage = None - self._validation_requests = None - - def fetch(self): - """ - Fetch a AccountInstance - - :returns: Fetched AccountInstance - :rtype: twilio.rest.api.v2010.account.AccountInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], ) + return AccountInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def update(self, friendly_name=values.unset, status=values.unset): + def update( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> AccountInstance: """ Update the AccountInstance - :param unicode friendly_name: FriendlyName to update - :param AccountInstance.Status status: Status to update the Account with + :param friendly_name: Update the human-readable description of this Account + :param status: - :returns: Updated AccountInstance - :rtype: twilio.rest.api.v2010.account.AccountInstance + :returns: The updated AccountInstance """ - data = values.of({'FriendlyName': friendly_name, 'Status': status, }) + + 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( - 'POST', - self._uri, - data=data, + 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'], ) + return AccountInstance(self._version, payload, sid=self._solution["sid"]) @property - def addresses(self): + def addresses(self) -> AddressList: """ Access the addresses - - :returns: twilio.rest.api.v2010.account.address.AddressList - :rtype: twilio.rest.api.v2010.account.address.AddressList """ if self._addresses is None: - self._addresses = AddressList(self._version, account_sid=self._solution['sid'], ) + self._addresses = AddressList( + self._version, + self._solution["sid"], + ) return self._addresses @property - def applications(self): + def applications(self) -> ApplicationList: """ Access the applications - - :returns: twilio.rest.api.v2010.account.application.ApplicationList - :rtype: twilio.rest.api.v2010.account.application.ApplicationList """ if self._applications is None: - self._applications = ApplicationList(self._version, account_sid=self._solution['sid'], ) + self._applications = ApplicationList( + self._version, + self._solution["sid"], + ) return self._applications @property - def authorized_connect_apps(self): + def authorized_connect_apps(self) -> AuthorizedConnectAppList: """ Access the authorized_connect_apps - - :returns: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppList - :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppList """ if self._authorized_connect_apps is None: self._authorized_connect_apps = AuthorizedConnectAppList( self._version, - account_sid=self._solution['sid'], + self._solution["sid"], ) return self._authorized_connect_apps @property - def available_phone_numbers(self): + def available_phone_numbers(self) -> AvailablePhoneNumberCountryList: """ Access the available_phone_numbers - - :returns: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryList - :rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryList """ if self._available_phone_numbers is None: self._available_phone_numbers = AvailablePhoneNumberCountryList( self._version, - account_sid=self._solution['sid'], + self._solution["sid"], ) return self._available_phone_numbers @property - def calls(self): + def balance(self) -> BalanceList: """ - Access the calls + Access the balance + """ + if self._balance is None: + self._balance = BalanceList( + self._version, + self._solution["sid"], + ) + return self._balance - :returns: twilio.rest.api.v2010.account.call.CallList - :rtype: twilio.rest.api.v2010.account.call.CallList + @property + def calls(self) -> CallList: + """ + Access the calls """ if self._calls is None: - self._calls = CallList(self._version, account_sid=self._solution['sid'], ) + self._calls = CallList( + self._version, + self._solution["sid"], + ) return self._calls @property - def conferences(self): + def conferences(self) -> ConferenceList: """ Access the conferences - - :returns: twilio.rest.api.v2010.account.conference.ConferenceList - :rtype: twilio.rest.api.v2010.account.conference.ConferenceList """ if self._conferences is None: - self._conferences = ConferenceList(self._version, account_sid=self._solution['sid'], ) + self._conferences = ConferenceList( + self._version, + self._solution["sid"], + ) return self._conferences @property - def connect_apps(self): + def connect_apps(self) -> ConnectAppList: """ Access the connect_apps - - :returns: twilio.rest.api.v2010.account.connect_app.ConnectAppList - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppList """ if self._connect_apps is None: - self._connect_apps = ConnectAppList(self._version, account_sid=self._solution['sid'], ) + self._connect_apps = ConnectAppList( + self._version, + self._solution["sid"], + ) return self._connect_apps @property - def incoming_phone_numbers(self): + def incoming_phone_numbers(self) -> IncomingPhoneNumberList: """ Access the incoming_phone_numbers - - :returns: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberList - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberList """ if self._incoming_phone_numbers is None: self._incoming_phone_numbers = IncomingPhoneNumberList( self._version, - account_sid=self._solution['sid'], + self._solution["sid"], ) return self._incoming_phone_numbers @property - def keys(self): + def keys(self) -> KeyList: """ Access the keys - - :returns: twilio.rest.api.v2010.account.key.KeyList - :rtype: twilio.rest.api.v2010.account.key.KeyList """ if self._keys is None: - self._keys = KeyList(self._version, account_sid=self._solution['sid'], ) + self._keys = KeyList( + self._version, + self._solution["sid"], + ) return self._keys @property - def messages(self): + def messages(self) -> MessageList: """ Access the messages - - :returns: twilio.rest.api.v2010.account.message.MessageList - :rtype: twilio.rest.api.v2010.account.message.MessageList """ if self._messages is None: - self._messages = MessageList(self._version, account_sid=self._solution['sid'], ) + self._messages = MessageList( + self._version, + self._solution["sid"], + ) return self._messages @property - def new_keys(self): + def new_keys(self) -> NewKeyList: """ Access the new_keys - - :returns: twilio.rest.api.v2010.account.new_key.NewKeyList - :rtype: twilio.rest.api.v2010.account.new_key.NewKeyList """ if self._new_keys is None: - self._new_keys = NewKeyList(self._version, account_sid=self._solution['sid'], ) + self._new_keys = NewKeyList( + self._version, + self._solution["sid"], + ) return self._new_keys @property - def new_signing_keys(self): + def new_signing_keys(self) -> NewSigningKeyList: """ Access the new_signing_keys - - :returns: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyList - :rtype: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyList """ if self._new_signing_keys is None: - self._new_signing_keys = NewSigningKeyList(self._version, account_sid=self._solution['sid'], ) + self._new_signing_keys = NewSigningKeyList( + self._version, + self._solution["sid"], + ) return self._new_signing_keys @property - def notifications(self): + def notifications(self) -> NotificationList: """ Access the notifications - - :returns: twilio.rest.api.v2010.account.notification.NotificationList - :rtype: twilio.rest.api.v2010.account.notification.NotificationList """ if self._notifications is None: - self._notifications = NotificationList(self._version, account_sid=self._solution['sid'], ) + self._notifications = NotificationList( + self._version, + self._solution["sid"], + ) return self._notifications @property - def outgoing_caller_ids(self): + def outgoing_caller_ids(self) -> OutgoingCallerIdList: """ Access the outgoing_caller_ids - - :returns: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdList - :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdList """ if self._outgoing_caller_ids is None: - self._outgoing_caller_ids = OutgoingCallerIdList(self._version, account_sid=self._solution['sid'], ) + self._outgoing_caller_ids = OutgoingCallerIdList( + self._version, + self._solution["sid"], + ) return self._outgoing_caller_ids @property - def queues(self): + def queues(self) -> QueueList: """ Access the queues - - :returns: twilio.rest.api.v2010.account.queue.QueueList - :rtype: twilio.rest.api.v2010.account.queue.QueueList """ if self._queues is None: - self._queues = QueueList(self._version, account_sid=self._solution['sid'], ) + self._queues = QueueList( + self._version, + self._solution["sid"], + ) return self._queues @property - def recordings(self): + def recordings(self) -> RecordingList: """ Access the recordings - - :returns: twilio.rest.api.v2010.account.recording.RecordingList - :rtype: twilio.rest.api.v2010.account.recording.RecordingList """ if self._recordings is None: - self._recordings = RecordingList(self._version, account_sid=self._solution['sid'], ) + self._recordings = RecordingList( + self._version, + self._solution["sid"], + ) return self._recordings @property - def signing_keys(self): + def short_codes(self) -> ShortCodeList: """ - Access the signing_keys + Access the short_codes + """ + if self._short_codes is None: + self._short_codes = ShortCodeList( + self._version, + self._solution["sid"], + ) + return self._short_codes - :returns: twilio.rest.api.v2010.account.signing_key.SigningKeyList - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyList + @property + def signing_keys(self) -> SigningKeyList: + """ + Access the signing_keys """ if self._signing_keys is None: - self._signing_keys = SigningKeyList(self._version, account_sid=self._solution['sid'], ) + self._signing_keys = SigningKeyList( + self._version, + self._solution["sid"], + ) return self._signing_keys @property - def sip(self): + def sip(self) -> SipList: """ Access the sip - - :returns: twilio.rest.api.v2010.account.sip.SipList - :rtype: twilio.rest.api.v2010.account.sip.SipList """ if self._sip is None: - self._sip = SipList(self._version, account_sid=self._solution['sid'], ) + self._sip = SipList( + self._version, + self._solution["sid"], + ) return self._sip @property - def short_codes(self): - """ - Access the short_codes - - :returns: twilio.rest.api.v2010.account.short_code.ShortCodeList - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeList - """ - if self._short_codes is None: - self._short_codes = ShortCodeList(self._version, account_sid=self._solution['sid'], ) - return self._short_codes - - @property - def tokens(self): + def tokens(self) -> TokenList: """ Access the tokens - - :returns: twilio.rest.api.v2010.account.token.TokenList - :rtype: twilio.rest.api.v2010.account.token.TokenList """ if self._tokens is None: - self._tokens = TokenList(self._version, account_sid=self._solution['sid'], ) + self._tokens = TokenList( + self._version, + self._solution["sid"], + ) return self._tokens @property - def transcriptions(self): + def transcriptions(self) -> TranscriptionList: """ Access the transcriptions - - :returns: twilio.rest.api.v2010.account.transcription.TranscriptionList - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionList """ if self._transcriptions is None: - self._transcriptions = TranscriptionList(self._version, account_sid=self._solution['sid'], ) + self._transcriptions = TranscriptionList( + self._version, + self._solution["sid"], + ) return self._transcriptions @property - def usage(self): + def usage(self) -> UsageList: """ Access the usage - - :returns: twilio.rest.api.v2010.account.usage.UsageList - :rtype: twilio.rest.api.v2010.account.usage.UsageList """ if self._usage is None: - self._usage = UsageList(self._version, account_sid=self._solution['sid'], ) + self._usage = UsageList( + self._version, + self._solution["sid"], + ) return self._usage @property - def validation_requests(self): + def validation_requests(self) -> ValidationRequestList: """ Access the validation_requests - - :returns: twilio.rest.api.v2010.account.validation_request.ValidationRequestList - :rtype: twilio.rest.api.v2010.account.validation_request.ValidationRequestList """ if self._validation_requests is None: - self._validation_requests = ValidationRequestList(self._version, account_sid=self._solution['sid'], ) + self._validation_requests = ValidationRequestList( + self._version, + self._solution["sid"], + ) return self._validation_requests - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class AccountInstance(InstanceResource): - """ """ - - class Status(object): - ACTIVE = "active" - SUSPENDED = "suspended" - CLOSED = "closed" - - class Type(object): - TRIAL = "Trial" - FULL = "Full" - - def __init__(self, version, payload, sid=None): """ - Initialize the AccountInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: twilio.rest.api.v2010.account.AccountInstance - :rtype: twilio.rest.api.v2010.account.AccountInstance - """ - super(AccountInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'auth_token': payload['auth_token'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'friendly_name': payload['friendly_name'], - 'owner_account_sid': payload['owner_account_sid'], - 'sid': payload['sid'], - 'status': payload['status'], - 'subresource_uris': payload['subresource_uris'], - 'type': payload['type'], - 'uri': payload['uri'], - } - - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.api.v2010.account.AccountContext - """ - if self._context is None: - self._context = AccountContext(self._version, sid=self._solution['sid'], ) - return self._context +class AccountPage(Page): - @property - def auth_token(self): - """ - :returns: The authorization token for this account - :rtype: unicode + def get_instance(self, payload: Dict[str, Any]) -> AccountInstance: """ - return self._properties['auth_token'] + Build an instance of AccountInstance - @property - def date_created(self): + :param payload: Payload response from the API """ - :returns: The date this account was created - :rtype: datetime - """ - return self._properties['date_created'] + return AccountInstance(self._version, payload) - @property - def date_updated(self): + def __repr__(self) -> str: """ - :returns: The date this account was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + Provide a friendly representation - @property - def friendly_name(self): - """ - :returns: A human readable description of this account - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['friendly_name'] + return "" - @property - def owner_account_sid(self): - """ - :returns: The unique 34 character id representing the parent of this account - :rtype: unicode - """ - return self._properties['owner_account_sid'] - @property - def sid(self): - """ - :returns: A 34 character string that uniquely identifies this resource. - :rtype: unicode - """ - return self._properties['sid'] +class AccountList(ListResource): - @property - def status(self): + def __init__(self, version: Version): """ - :returns: The status of this account - :rtype: AccountInstance.Status - """ - return self._properties['status'] + Initialize the AccountList - @property - def subresource_uris(self): - """ - :returns: Account Instance Subresources - :rtype: unicode - """ - return self._properties['subresource_uris'] + :param version: Version that contains the resource - @property - def type(self): - """ - :returns: The type of this account - :rtype: AccountInstance.Type """ - return self._properties['type'] + super().__init__(version) - @property - def uri(self): - """ - :returns: The URI for this resource, relative to `https://api.twilio.com` - :rtype: unicode - """ - return self._properties['uri'] + self._uri = "/Accounts.json" - def fetch(self): + def create( + self, friendly_name: Union[str, object] = values.unset + ) -> AccountInstance: """ - Fetch a AccountInstance + Create the AccountInstance - :returns: Fetched AccountInstance - :rtype: twilio.rest.api.v2010.account.AccountInstance - """ - return self._proxy.fetch() + :param friendly_name: A human readable description of the account to create, defaults to `SubAccount Created at {YYYY-MM-DD HH:MM meridian}` - def update(self, friendly_name=values.unset, status=values.unset): + :returns: The created AccountInstance """ - Update the AccountInstance - :param unicode friendly_name: FriendlyName to update - :param AccountInstance.Status status: Status to update the Account with + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: Updated AccountInstance - :rtype: twilio.rest.api.v2010.account.AccountInstance - """ - return self._proxy.update(friendly_name=friendly_name, status=status, ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def addresses(self): - """ - Access the addresses - - :returns: twilio.rest.api.v2010.account.address.AddressList - :rtype: twilio.rest.api.v2010.account.address.AddressList - """ - return self._proxy.addresses + headers["Accept"] = "application/json" - @property - def applications(self): - """ - Access the applications + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: twilio.rest.api.v2010.account.application.ApplicationList - :rtype: twilio.rest.api.v2010.account.application.ApplicationList - """ - return self._proxy.applications + return AccountInstance(self._version, payload) - @property - def authorized_connect_apps(self): + async def create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> AccountInstance: """ - Access the authorized_connect_apps + Asynchronously create the AccountInstance - :returns: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppList - :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppList - """ - return self._proxy.authorized_connect_apps + :param friendly_name: A human readable description of the account to create, defaults to `SubAccount Created at {YYYY-MM-DD HH:MM meridian}` - @property - def available_phone_numbers(self): + :returns: The created AccountInstance """ - Access the available_phone_numbers - :returns: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryList - :rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryList - """ - return self._proxy.available_phone_numbers + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def calls(self): - """ - Access the calls + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: twilio.rest.api.v2010.account.call.CallList - :rtype: twilio.rest.api.v2010.account.call.CallList - """ - return self._proxy.calls + headers["Accept"] = "application/json" - @property - def conferences(self): - """ - Access the conferences - - :returns: twilio.rest.api.v2010.account.conference.ConferenceList - :rtype: twilio.rest.api.v2010.account.conference.ConferenceList - """ - return self._proxy.conferences + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def connect_apps(self): - """ - Access the connect_apps + return AccountInstance(self._version, payload) - :returns: twilio.rest.api.v2010.account.connect_app.ConnectAppList - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppList + 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]: """ - return self._proxy.connect_apps + 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. - @property - def incoming_phone_numbers(self): - """ - Access the incoming_phone_numbers + :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: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberList - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberList + :returns: Generator that will yield up to limit results """ - return self._proxy.incoming_phone_numbers + limits = self._version.read_limits(limit, page_size) + page = self.page( + friendly_name=friendly_name, status=status, page_size=limits["page_size"] + ) - @property - def keys(self): - """ - Access the keys + return self._version.stream(page, limits["limit"]) - :returns: twilio.rest.api.v2010.account.key.KeyList - :rtype: twilio.rest.api.v2010.account.key.KeyList + 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]: """ - return self._proxy.keys + 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. - @property - def messages(self): - """ - Access the messages + :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: twilio.rest.api.v2010.account.message.MessageList - :rtype: twilio.rest.api.v2010.account.message.MessageList + :returns: Generator that will yield up to limit results """ - return self._proxy.messages + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, status=status, page_size=limits["page_size"] + ) - @property - def new_keys(self): - """ - Access the new_keys + return self._version.stream_async(page, limits["limit"]) - :returns: twilio.rest.api.v2010.account.new_key.NewKeyList - :rtype: twilio.rest.api.v2010.account.new_key.NewKeyList + 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]: """ - return self._proxy.new_keys + Lists AccountInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def new_signing_keys(self): - """ - Access the new_signing_keys + :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, + ) + ) - :returns: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyList - :rtype: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyList + 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]: """ - return self._proxy.new_signing_keys + 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. - @property - def notifications(self): - """ - Access the notifications + :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, + ) + ] - :returns: twilio.rest.api.v2010.account.notification.NotificationList - :rtype: twilio.rest.api.v2010.account.notification.NotificationList + 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: """ - return self._proxy.notifications + Retrieve a single page of AccountInstance records from the API. + Request is executed immediately - @property - def outgoing_caller_ids(self): - """ - Access the outgoing_caller_ids + :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: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdList - :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdList + :returns: Page of AccountInstance """ - return self._proxy.outgoing_caller_ids + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def queues(self): - """ - Access the queues + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: twilio.rest.api.v2010.account.queue.QueueList - :rtype: twilio.rest.api.v2010.account.queue.QueueList - """ - return self._proxy.queues + headers["Accept"] = "application/json" - @property - def recordings(self): - """ - Access the recordings + 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 - :returns: twilio.rest.api.v2010.account.recording.RecordingList - :rtype: twilio.rest.api.v2010.account.recording.RecordingList - """ - return self._proxy.recordings + :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 - @property - def signing_keys(self): + :returns: Page of AccountInstance """ - Access the signing_keys + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: twilio.rest.api.v2010.account.signing_key.SigningKeyList - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyList - """ - return self._proxy.signing_keys + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def sip(self): - """ - Access the sip + headers["Accept"] = "application/json" - :returns: twilio.rest.api.v2010.account.sip.SipList - :rtype: twilio.rest.api.v2010.account.sip.SipList - """ - return self._proxy.sip + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AccountPage(self._version, response) - @property - def short_codes(self): + def get_page(self, target_url: str) -> AccountPage: """ - Access the short_codes + Retrieve a specific page of AccountInstance records from the API. + Request is executed immediately - :returns: twilio.rest.api.v2010.account.short_code.ShortCodeList - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeList - """ - return self._proxy.short_codes + :param target_url: API-generated URL for the requested results page - @property - def tokens(self): + :returns: Page of AccountInstance """ - Access the tokens + response = self._version.domain.twilio.request("GET", target_url) + return AccountPage(self._version, response) - :returns: twilio.rest.api.v2010.account.token.TokenList - :rtype: twilio.rest.api.v2010.account.token.TokenList + async def get_page_async(self, target_url: str) -> AccountPage: """ - return self._proxy.tokens + Asynchronously retrieve a specific page of AccountInstance records from the API. + Request is executed immediately - @property - def transcriptions(self): - """ - Access the transcriptions + :param target_url: API-generated URL for the requested results page - :returns: twilio.rest.api.v2010.account.transcription.TranscriptionList - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionList + :returns: Page of AccountInstance """ - return self._proxy.transcriptions + response = await self._version.domain.twilio.request_async("GET", target_url) + return AccountPage(self._version, response) - @property - def usage(self): + def get(self, sid: str) -> AccountContext: """ - Access the usage + Constructs a AccountContext - :returns: twilio.rest.api.v2010.account.usage.UsageList - :rtype: twilio.rest.api.v2010.account.usage.UsageList + :param sid: The Account Sid that uniquely identifies the account to update """ - return self._proxy.usage + return AccountContext(self._version, sid=sid) - @property - def validation_requests(self): + def __call__(self, sid: str) -> AccountContext: """ - Access the validation_requests + Constructs a AccountContext - :returns: twilio.rest.api.v2010.account.validation_request.ValidationRequestList - :rtype: twilio.rest.api.v2010.account.validation_request.ValidationRequestList + :param sid: The Account Sid that uniquely identifies the account to update """ - return self._proxy.validation_requests + return AccountContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/api/v2010/account/address/__init__.py b/twilio/rest/api/v2010/account/address/__init__.py index 9f7caad13a..77fc702ccc 100644 --- a/twilio/rest/api/v2010/account/address/__init__.py +++ b/twilio/rest/api/v2010/account/address/__init__.py @@ -1,612 +1,913 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 +from twilio.rest.api.v2010.account.address.dependent_phone_number import ( + DependentPhoneNumberList, +) -class AddressList(ListResource): - """ """ +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 - def __init__(self, version, account_sid): + @property + def _proxy(self) -> "AddressContext": """ - Initialize the AddressList - - :param Version version: Version that contains the resource - :param account_sid: The account_sid + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: twilio.rest.api.v2010.account.address.AddressList - :rtype: twilio.rest.api.v2010.account.address.AddressList + :returns: AddressContext for this AddressInstance """ - super(AddressList, self).__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, street, city, region, postal_code, iso_country, - friendly_name=values.unset, emergency_enabled=values.unset, - auto_correct_address=values.unset): - """ - Create a new AddressInstance - - :param unicode customer_name: The customer_name - :param unicode street: The street - :param unicode city: The city - :param unicode region: The region - :param unicode postal_code: The postal_code - :param unicode iso_country: The iso_country - :param unicode friendly_name: The friendly_name - :param bool emergency_enabled: The emergency_enabled - :param bool auto_correct_address: The auto_correct_address - - :returns: Newly created AddressInstance - :rtype: twilio.rest.api.v2010.account.address.AddressInstance - """ - data = values.of({ - 'CustomerName': customer_name, - 'Street': street, - 'City': city, - 'Region': region, - 'PostalCode': postal_code, - 'IsoCountry': iso_country, - 'FriendlyName': friendly_name, - 'EmergencyEnabled': emergency_enabled, - 'AutoCorrectAddress': auto_correct_address, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return AddressInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + if self._context is None: + self._context = AddressContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - def stream(self, customer_name=values.unset, friendly_name=values.unset, - iso_country=values.unset, limit=None, page_size=None): + def delete(self) -> bool: """ - 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. + Deletes the AddressInstance - :param unicode customer_name: The customer_name - :param unicode friendly_name: The friendly_name - :param unicode iso_country: The iso_country - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.address.AddressInstance] + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) - - page = self.page( - customer_name=customer_name, - friendly_name=friendly_name, - iso_country=iso_country, - page_size=limits['page_size'], - ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) + return self._proxy.delete() - def list(self, customer_name=values.unset, friendly_name=values.unset, - iso_country=values.unset, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists AddressInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the AddressInstance - :param unicode customer_name: The customer_name - :param unicode friendly_name: The friendly_name - :param unicode iso_country: The iso_country - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.address.AddressInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream( - customer_name=customer_name, - friendly_name=friendly_name, - iso_country=iso_country, - limit=limit, - page_size=page_size, - )) + return await self._proxy.delete_async() - def page(self, customer_name=values.unset, friendly_name=values.unset, - iso_country=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch(self) -> "AddressInstance": """ - Retrieve a single page of AddressInstance records from the API. - Request is executed immediately + Fetch the AddressInstance - :param unicode customer_name: The customer_name - :param unicode friendly_name: The friendly_name - :param unicode iso_country: The iso_country - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of AddressInstance - :rtype: twilio.rest.api.v2010.account.address.AddressPage + :returns: The fetched AddressInstance """ - params = values.of({ - 'CustomerName': customer_name, - 'FriendlyName': friendly_name, - 'IsoCountry': iso_country, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return AddressPage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "AddressInstance": """ - Retrieve a specific page of AddressInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the AddressInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of AddressInstance - :rtype: twilio.rest.api.v2010.account.address.AddressPage + :returns: The fetched AddressInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return AddressPage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def get(self, 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": """ - Constructs a AddressContext - - :param sid: The sid + Update the AddressInstance - :returns: twilio.rest.api.v2010.account.address.AddressContext - :rtype: twilio.rest.api.v2010.account.address.AddressContext - """ - return AddressContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + :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. - def __call__(self, sid): + :returns: The updated AddressInstance """ - Constructs a AddressContext + 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, + ) - :param sid: The 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 + """ + 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, + ) - :returns: twilio.rest.api.v2010.account.address.AddressContext - :rtype: twilio.rest.api.v2010.account.address.AddressContext + @property + def dependent_phone_numbers(self) -> DependentPhoneNumberList: """ - return AddressContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + Access the dependent_phone_numbers + """ + return self._proxy.dependent_phone_numbers - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class AddressPage(Page): - """ """ +class AddressContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str, sid: str): """ - Initialize the AddressPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The account_sid + Initialize the AddressContext - :returns: twilio.rest.api.v2010.account.address.AddressPage - :rtype: twilio.rest.api.v2010.account.address.AddressPage + :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(AddressPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of AddressInstance + Deletes the AddressInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.api.v2010.account.address.AddressInstance - :rtype: twilio.rest.api.v2010.account.address.AddressInstance + :returns: True if delete succeeds, False otherwise """ - return AddressInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the AddressInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class AddressContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, account_sid, sid): + def fetch(self) -> AddressInstance: """ - Initialize the AddressContext + Fetch the AddressInstance - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param sid: The sid - :returns: twilio.rest.api.v2010.account.address.AddressContext - :rtype: twilio.rest.api.v2010.account.address.AddressContext + :returns: The fetched AddressInstance """ - super(AddressContext, self).__init__(version) - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/Addresses/{sid}.json'.format(**self._solution) + headers = values.of({}) - # Dependents - self._dependent_phone_numbers = None + headers["Accept"] = "application/json" - def delete(self): - """ - Deletes the AddressInstance + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + return AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - def fetch(self): + async def fetch_async(self) -> AddressInstance: """ - Fetch a AddressInstance + Asynchronous coroutine to fetch the AddressInstance + - :returns: Fetched AddressInstance - :rtype: twilio.rest.api.v2010.account.address.AddressInstance + :returns: The fetched AddressInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def update(self, friendly_name=values.unset, customer_name=values.unset, - street=values.unset, city=values.unset, region=values.unset, - postal_code=values.unset, emergency_enabled=values.unset, - auto_correct_address=values.unset): + 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 unicode friendly_name: The friendly_name - :param unicode customer_name: The customer_name - :param unicode street: The street - :param unicode city: The city - :param unicode region: The region - :param unicode postal_code: The postal_code - :param bool emergency_enabled: The emergency_enabled - :param bool auto_correct_address: The auto_correct_address - - :returns: Updated AddressInstance - :rtype: twilio.rest.api.v2010.account.address.AddressInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'CustomerName': customer_name, - 'Street': street, - 'City': city, - 'Region': region, - 'PostalCode': postal_code, - 'EmergencyEnabled': emergency_enabled, - 'AutoCorrectAddress': auto_correct_address, - }) + :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( - 'POST', - self._uri, - data=data, + 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'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) @property - def dependent_phone_numbers(self): + def dependent_phone_numbers(self) -> DependentPhoneNumberList: """ Access the dependent_phone_numbers - - :returns: twilio.rest.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberList - :rtype: twilio.rest.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberList """ if self._dependent_phone_numbers is None: self._dependent_phone_numbers = DependentPhoneNumberList( self._version, - account_sid=self._solution['account_sid'], - address_sid=self._solution['sid'], + self._solution["account_sid"], + self._solution["sid"], ) return self._dependent_phone_numbers - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class AddressInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid, sid=None): - """ - Initialize the AddressInstance - - :returns: twilio.rest.api.v2010.account.address.AddressInstance - :rtype: twilio.rest.api.v2010.account.address.AddressInstance - """ - super(AddressInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'city': payload['city'], - 'customer_name': payload['customer_name'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'friendly_name': payload['friendly_name'], - 'iso_country': payload['iso_country'], - 'postal_code': payload['postal_code'], - 'region': payload['region'], - 'sid': payload['sid'], - 'street': payload['street'], - 'uri': payload['uri'], - 'emergency_enabled': payload['emergency_enabled'], - 'validated': payload['validated'], - } - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } +class AddressPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> AddressInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of AddressInstance - :returns: AddressContext for this AddressInstance - :rtype: twilio.rest.api.v2010.account.address.AddressContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = AddressContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + return AddressInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def city(self): - """ - :returns: The city - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['city'] + return "" - @property - def customer_name(self): - """ - :returns: The customer_name - :rtype: unicode - """ - return self._properties['customer_name'] - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] +class AddressList(ListResource): - @property - def date_updated(self): + def __init__(self, version: Version, account_sid: str): """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + Initialize the AddressList - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] + :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. - @property - def iso_country(self): - """ - :returns: The iso_country - :rtype: unicode """ - return self._properties['iso_country'] + super().__init__(version) - @property - def postal_code(self): - """ - :returns: The postal_code - :rtype: unicode - """ - return self._properties['postal_code'] + # 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"}) - @property - def region(self): - """ - :returns: The region - :rtype: unicode - """ - return self._properties['region'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + headers["Accept"] = "application/json" - @property - def street(self): - """ - :returns: The street - :rtype: unicode + 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]: """ - return self._properties['street'] + 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. - @property - def uri(self): + :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 """ - :returns: The uri - :rtype: unicode + 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]: """ - return self._properties['uri'] + 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. - @property - def emergency_enabled(self): + :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 """ - :returns: The emergency_enabled - :rtype: bool + 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]: """ - return self._properties['emergency_enabled'] + Lists AddressInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def validated(self): + :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: """ - :returns: The validated - :rtype: bool + 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 """ - return self._properties['validated'] + 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"}) - def delete(self): + 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 """ - Deletes the 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, + } + ) - :returns: True if delete succeeds, False otherwise - :rtype: bool + headers = values.of({"Content-Type": "application/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: """ - return self._proxy.delete() + 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 - def fetch(self): + :returns: Page of AddressInstance """ - Fetch a AddressInstance + response = self._version.domain.twilio.request("GET", target_url) + return AddressPage(self._version, response, self._solution) - :returns: Fetched AddressInstance - :rtype: twilio.rest.api.v2010.account.address.AddressInstance + async def get_page_async(self, target_url: str) -> AddressPage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of AddressInstance records from the API. + Request is executed immediately - def update(self, friendly_name=values.unset, customer_name=values.unset, - street=values.unset, city=values.unset, region=values.unset, - postal_code=values.unset, emergency_enabled=values.unset, - auto_correct_address=values.unset): + :param target_url: API-generated URL for the requested results page + + :returns: Page of AddressInstance """ - Update the AddressInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return AddressPage(self._version, response, self._solution) - :param unicode friendly_name: The friendly_name - :param unicode customer_name: The customer_name - :param unicode street: The street - :param unicode city: The city - :param unicode region: The region - :param unicode postal_code: The postal_code - :param bool emergency_enabled: The emergency_enabled - :param bool auto_correct_address: The auto_correct_address + def get(self, sid: str) -> AddressContext: + """ + Constructs a AddressContext - :returns: Updated AddressInstance - :rtype: twilio.rest.api.v2010.account.address.AddressInstance + :param sid: The Twilio-provided string that uniquely identifies the Address resource to update. """ - 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, + return AddressContext( + self._version, account_sid=self._solution["account_sid"], sid=sid ) - @property - def dependent_phone_numbers(self): + def __call__(self, sid: str) -> AddressContext: """ - Access the dependent_phone_numbers + Constructs a AddressContext - :returns: twilio.rest.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberList - :rtype: twilio.rest.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberList + :param sid: The Twilio-provided string that uniquely identifies the Address resource to update. """ - return self._proxy.dependent_phone_numbers + return AddressContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/api/v2010/account/address/dependent_phone_number.py b/twilio/rest/api/v2010/account/address/dependent_phone_number.py index 39126bff44..504e69bc92 100644 --- a/twilio/rest/api/v2010/account/address/dependent_phone_number.py +++ b/twilio/rest/api/v2010/account/address/dependent_phone_number.py @@ -1,444 +1,374 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 DependentPhoneNumberList(ListResource): - """ """ - - def __init__(self, version, account_sid, address_sid): - """ - Initialize the DependentPhoneNumberList - - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param address_sid: The sid - - :returns: twilio.rest.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberList - :rtype: twilio.rest.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberList - """ - super(DependentPhoneNumberList, self).__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=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of DependentPhoneNumberInstance records from the API. - Request is executed immediately +class DependentPhoneNumberInstance(InstanceResource): - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + class AddressRequirement(object): + NONE = "none" + ANY = "any" + LOCAL = "local" + FOREIGN = "foreign" - :returns: Page of DependentPhoneNumberInstance - :rtype: twilio.rest.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberPage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + class EmergencyStatus(object): + ACTIVE = "Active" + INACTIVE = "Inactive" - response = self._version.page( - 'GET', - self._uri, - params=params, + """ + :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" ) - - return DependentPhoneNumberPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of DependentPhoneNumberInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of DependentPhoneNumberInstance - :rtype: twilio.rest.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, + } - return DependentPhoneNumberPage(self._version, response, self._solution) - - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) class DependentPhoneNumberPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the DependentPhoneNumberPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The account_sid - :param address_sid: The sid - - :returns: twilio.rest.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberPage - :rtype: twilio.rest.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberPage - """ - super(DependentPhoneNumberPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - def get_instance(self, payload): + def get_instance(self, payload: Dict[str, Any]) -> DependentPhoneNumberInstance: """ Build an instance of DependentPhoneNumberInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberInstance - :rtype: twilio.rest.api.v2010.account.address.dependent_phone_number.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'], + account_sid=self._solution["account_sid"], + address_sid=self._solution["address_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class DependentPhoneNumberInstance(InstanceResource): - """ """ +class DependentPhoneNumberList(ListResource): - class AddressRequirement(object): - NONE = "none" - ANY = "any" - LOCAL = "local" - FOREIGN = "foreign" + def __init__(self, version: Version, account_sid: str, address_sid: str): + """ + Initialize the DependentPhoneNumberList - class EmergencyStatus(object): - ACTIVE = "Active" - INACTIVE = "Inactive" + :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. - def __init__(self, version, payload, account_sid, address_sid): """ - Initialize the DependentPhoneNumberInstance + super().__init__(version) - :returns: twilio.rest.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberInstance - :rtype: twilio.rest.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberInstance - """ - super(DependentPhoneNumberInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'friendly_name': payload['friendly_name'], - 'phone_number': payload['phone_number'], - 'voice_url': payload['voice_url'], - 'voice_method': payload['voice_method'], - 'voice_fallback_method': payload['voice_fallback_method'], - 'voice_fallback_url': payload['voice_fallback_url'], - 'voice_caller_id_lookup': payload['voice_caller_id_lookup'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'sms_fallback_method': payload['sms_fallback_method'], - 'sms_fallback_url': payload['sms_fallback_url'], - 'sms_method': payload['sms_method'], - 'sms_url': payload['sms_url'], - 'address_requirements': payload['address_requirements'], - 'capabilities': payload['capabilities'], - 'status_callback': payload['status_callback'], - 'status_callback_method': payload['status_callback_method'], - 'api_version': payload['api_version'], - 'sms_application_sid': payload['sms_application_sid'], - 'voice_application_sid': payload['voice_application_sid'], - 'trunk_sid': payload['trunk_sid'], - 'emergency_status': payload['emergency_status'], - 'emergency_address_sid': payload['emergency_address_sid'], - 'uri': payload['uri'], + # 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 + ) - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'address_sid': address_sid, } - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DependentPhoneNumberInstance]: """ - return self._properties['sid'] + 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. - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_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) - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['friendly_name'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def phone_number(self): - """ - :returns: The phone_number - :rtype: unicode - """ - return self._properties['phone_number'] + return self._version.stream(page, limits["limit"]) - @property - def voice_url(self): - """ - :returns: The voice_url - :rtype: unicode + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DependentPhoneNumberInstance]: """ - return self._properties['voice_url'] + 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. - @property - def voice_method(self): - """ - :returns: The voice_method - :rtype: unicode - """ - return self._properties['voice_method'] + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - @property - def voice_fallback_method(self): - """ - :returns: The voice_fallback_method - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['voice_fallback_method'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def voice_fallback_url(self): - """ - :returns: The voice_fallback_url - :rtype: unicode - """ - return self._properties['voice_fallback_url'] + return self._version.stream_async(page, limits["limit"]) - @property - def voice_caller_id_lookup(self): - """ - :returns: The voice_caller_id_lookup - :rtype: bool + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DependentPhoneNumberInstance]: """ - return self._properties['voice_caller_id_lookup'] + Lists DependentPhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - @property - def date_updated(self): + :returns: list that will contain up to limit results """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def sms_fallback_method(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DependentPhoneNumberInstance]: """ - :returns: The sms_fallback_method - :rtype: unicode - """ - return self._properties['sms_fallback_method'] + 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. - @property - def sms_fallback_url(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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: """ - :returns: The sms_fallback_url - :rtype: unicode - """ - return self._properties['sms_fallback_url'] + Retrieve a single page of DependentPhoneNumberInstance records from the API. + Request is executed immediately - @property - def sms_method(self): - """ - :returns: The sms_method - :rtype: unicode - """ - return self._properties['sms_method'] + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - @property - def sms_url(self): - """ - :returns: The sms_url - :rtype: unicode + :returns: Page of DependentPhoneNumberInstance """ - return self._properties['sms_url'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def address_requirements(self): - """ - :returns: The address_requirements - :rtype: DependentPhoneNumberInstance.AddressRequirement - """ - return self._properties['address_requirements'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def capabilities(self): - """ - :returns: The capabilities - :rtype: dict - """ - return self._properties['capabilities'] + headers["Accept"] = "application/json" - @property - def status_callback(self): - """ - :returns: The status_callback - :rtype: unicode - """ - return self._properties['status_callback'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DependentPhoneNumberPage(self._version, response, self._solution) - @property - def status_callback_method(self): - """ - :returns: The status_callback_method - :rtype: unicode + 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: """ - return self._properties['status_callback_method'] + Asynchronously retrieve a single page of DependentPhoneNumberInstance records from the API. + Request is executed immediately - @property - def api_version(self): - """ - :returns: The api_version - :rtype: unicode - """ - return self._properties['api_version'] + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - @property - def sms_application_sid(self): - """ - :returns: The sms_application_sid - :rtype: unicode + :returns: Page of DependentPhoneNumberInstance """ - return self._properties['sms_application_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def voice_application_sid(self): - """ - :returns: The voice_application_sid - :rtype: unicode - """ - return self._properties['voice_application_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def trunk_sid(self): - """ - :returns: The trunk_sid - :rtype: unicode - """ - return self._properties['trunk_sid'] + headers["Accept"] = "application/json" - @property - def emergency_status(self): - """ - :returns: The emergency_status - :rtype: DependentPhoneNumberInstance.EmergencyStatus - """ - return self._properties['emergency_status'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DependentPhoneNumberPage(self._version, response, self._solution) - @property - def emergency_address_sid(self): + def get_page(self, target_url: str) -> DependentPhoneNumberPage: """ - :returns: The emergency_address_sid - :rtype: unicode + 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 """ - return self._properties['emergency_address_sid'] + response = self._version.domain.twilio.request("GET", target_url) + return DependentPhoneNumberPage(self._version, response, self._solution) - @property - def uri(self): + async def get_page_async(self, target_url: str) -> DependentPhoneNumberPage: """ - :returns: The uri - :rtype: unicode + 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 """ - return self._properties['uri'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return DependentPhoneNumberPage(self._version, response, self._solution) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/api/v2010/account/application.py b/twilio/rest/api/v2010/account/application.py index 315a744cba..555ab72b4a 100644 --- a/twilio/rest/api/v2010/account/application.py +++ b/twilio/rest/api/v2010/account/application.py @@ -1,667 +1,984 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 ApplicationList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the ApplicationList - - :param Version version: Version that contains the resource - :param account_sid: A string that uniquely identifies this resource - - :returns: twilio.rest.api.v2010.account.application.ApplicationList - :rtype: twilio.rest.api.v2010.account.application.ApplicationList - """ - super(ApplicationList, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Applications.json'.format(**self._solution) - - def create(self, friendly_name, api_version=values.unset, - voice_url=values.unset, voice_method=values.unset, - voice_fallback_url=values.unset, voice_fallback_method=values.unset, - status_callback=values.unset, status_callback_method=values.unset, - voice_caller_id_lookup=values.unset, sms_url=values.unset, - sms_method=values.unset, sms_fallback_url=values.unset, - sms_fallback_method=values.unset, sms_status_callback=values.unset, - message_status_callback=values.unset): - """ - Create a new ApplicationInstance - - :param unicode friendly_name: The friendly_name - :param unicode api_version: The API version to use - :param unicode voice_url: URL Twilio will make requests to when relieving a call - :param unicode voice_method: HTTP method to use with the URL - :param unicode voice_fallback_url: Fallback URL - :param unicode voice_fallback_method: HTTP method to use with the fallback url - :param unicode status_callback: URL to hit with status updates - :param unicode status_callback_method: HTTP method to use with the status callback - :param bool voice_caller_id_lookup: True or False - :param unicode sms_url: URL Twilio will request when receiving an SMS - :param unicode sms_method: HTTP method to use with sms_url - :param unicode sms_fallback_url: Fallback URL if there's an error parsing TwiML - :param unicode sms_fallback_method: HTTP method to use with sms_fallback_method - :param unicode sms_status_callback: URL Twilio with request with status updates - :param unicode message_status_callback: URL to make requests to with status updates - - :returns: Newly created ApplicationInstance - :rtype: twilio.rest.api.v2010.account.application.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': 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, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, +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" ) - return ApplicationInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[ApplicationContext] = None - def stream(self, friendly_name=values.unset, limit=None, page_size=None): + @property + def _proxy(self) -> "ApplicationContext": """ - 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 unicode friendly_name: Filter by friendly name - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.application.ApplicationInstance] + :returns: ApplicationContext for this ApplicationInstance """ - 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'], limits['page_limit']) + if self._context is None: + self._context = ApplicationContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - def list(self, friendly_name=values.unset, limit=None, page_size=None): + def delete(self) -> bool: """ - Lists ApplicationInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the ApplicationInstance - :param unicode friendly_name: Filter by friendly name - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.application.ApplicationInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(friendly_name=friendly_name, limit=limit, page_size=page_size, )) + return self._proxy.delete() - def page(self, friendly_name=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + async def delete_async(self) -> bool: """ - Retrieve a single page of ApplicationInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the ApplicationInstance - :param unicode friendly_name: Filter by friendly name - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of ApplicationInstance - :rtype: twilio.rest.api.v2010.account.application.ApplicationPage + :returns: True if delete succeeds, False otherwise """ - params = values.of({ - 'FriendlyName': friendly_name, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return await self._proxy.delete_async() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return ApplicationPage(self._version, response, self._solution) - - def get_page(self, target_url): + def fetch(self) -> "ApplicationInstance": """ - Retrieve a specific page of ApplicationInstance records from the API. - Request is executed immediately + Fetch the ApplicationInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of ApplicationInstance - :rtype: twilio.rest.api.v2010.account.application.ApplicationPage + :returns: The fetched ApplicationInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ApplicationPage(self._version, response, self._solution) + return self._proxy.fetch() - def get(self, sid): + async def fetch_async(self) -> "ApplicationInstance": """ - Constructs a ApplicationContext + Asynchronous coroutine to fetch the ApplicationInstance - :param sid: Fetch by unique Application Sid - :returns: twilio.rest.api.v2010.account.application.ApplicationContext - :rtype: twilio.rest.api.v2010.account.application.ApplicationContext + :returns: The fetched ApplicationInstance """ - return ApplicationContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return await self._proxy.fetch_async() - def __call__(self, 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": """ - Constructs a ApplicationContext - - :param sid: Fetch by unique Application Sid + Update the ApplicationInstance - :returns: twilio.rest.api.v2010.account.application.ApplicationContext - :rtype: twilio.rest.api.v2010.account.application.ApplicationContext + :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 ApplicationContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ApplicationPage(Page): - """ """ +class ApplicationContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str, sid: str): """ - Initialize the ApplicationPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: A string that uniquely identifies this resource + Initialize the ApplicationContext - :returns: twilio.rest.api.v2010.account.application.ApplicationPage - :rtype: twilio.rest.api.v2010.account.application.ApplicationPage + :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(ApplicationPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Applications/{sid}.json".format( + **self._solution + ) - def get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of ApplicationInstance + Deletes the ApplicationInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.api.v2010.account.application.ApplicationInstance - :rtype: twilio.rest.api.v2010.account.application.ApplicationInstance + :returns: True if delete succeeds, False otherwise """ - return ApplicationInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the ApplicationInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class ApplicationContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, account_sid, sid): + def fetch(self) -> ApplicationInstance: """ - Initialize the ApplicationContext + Fetch the ApplicationInstance - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param sid: Fetch by unique Application Sid - :returns: twilio.rest.api.v2010.account.application.ApplicationContext - :rtype: twilio.rest.api.v2010.account.application.ApplicationContext + :returns: The fetched ApplicationInstance """ - super(ApplicationContext, self).__init__(version) - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/Applications/{sid}.json'.format(**self._solution) + headers = values.of({}) - def delete(self): - """ - Deletes the ApplicationInstance + headers["Accept"] = "application/json" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return ApplicationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ApplicationInstance: """ - Fetch a ApplicationInstance + Asynchronous coroutine to fetch the ApplicationInstance + - :returns: Fetched ApplicationInstance - :rtype: twilio.rest.api.v2010.account.application.ApplicationInstance + :returns: The fetched ApplicationInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def update(self, friendly_name=values.unset, api_version=values.unset, - voice_url=values.unset, voice_method=values.unset, - voice_fallback_url=values.unset, voice_fallback_method=values.unset, - status_callback=values.unset, status_callback_method=values.unset, - voice_caller_id_lookup=values.unset, sms_url=values.unset, - sms_method=values.unset, sms_fallback_url=values.unset, - sms_fallback_method=values.unset, sms_status_callback=values.unset, - message_status_callback=values.unset): + 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 unicode friendly_name: Human readable description of this resource - :param unicode api_version: The API version to use - :param unicode voice_url: URL Twilio will make requests to when relieving a call - :param unicode voice_method: HTTP method to use with the URL - :param unicode voice_fallback_url: Fallback URL - :param unicode voice_fallback_method: HTTP method to use with the fallback url - :param unicode status_callback: URL to hit with status updates - :param unicode status_callback_method: HTTP method to use with the status callback - :param bool voice_caller_id_lookup: True or False - :param unicode sms_url: URL Twilio will request when receiving an SMS - :param unicode sms_method: HTTP method to use with sms_url - :param unicode sms_fallback_url: Fallback URL if there's an error parsing TwiML - :param unicode sms_fallback_method: HTTP method to use with sms_fallback_method - :param unicode sms_status_callback: URL Twilio with request with status updates - :param unicode message_status_callback: URL to make requests to with status updates - - :returns: Updated ApplicationInstance - :rtype: twilio.rest.api.v2010.account.application.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': 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, - }) + :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( - 'POST', - self._uri, - data=data, + 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'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ApplicationInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid, sid=None): - """ - Initialize the ApplicationInstance - - :returns: twilio.rest.api.v2010.account.application.ApplicationInstance - :rtype: twilio.rest.api.v2010.account.application.ApplicationInstance - """ - super(ApplicationInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'api_version': payload['api_version'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'friendly_name': payload['friendly_name'], - 'message_status_callback': payload['message_status_callback'], - 'sid': payload['sid'], - 'sms_fallback_method': payload['sms_fallback_method'], - 'sms_fallback_url': payload['sms_fallback_url'], - 'sms_method': payload['sms_method'], - 'sms_status_callback': payload['sms_status_callback'], - 'sms_url': payload['sms_url'], - 'status_callback': payload['status_callback'], - 'status_callback_method': payload['status_callback_method'], - 'uri': payload['uri'], - 'voice_caller_id_lookup': payload['voice_caller_id_lookup'], - 'voice_fallback_method': payload['voice_fallback_method'], - 'voice_fallback_url': payload['voice_fallback_url'], - 'voice_method': payload['voice_method'], - 'voice_url': payload['voice_url'], - } - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } +class ApplicationPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> ApplicationInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of ApplicationInstance - :returns: ApplicationContext for this ApplicationInstance - :rtype: twilio.rest.api.v2010.account.application.ApplicationContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = ApplicationContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + return ApplicationInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def account_sid(self): - """ - :returns: A string that uniquely identifies this resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def api_version(self): - """ - :returns: The API version to use - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['api_version'] + return "" - @property - def date_created(self): - """ - :returns: Date this resource was created - :rtype: datetime - """ - return self._properties['date_created'] - @property - def date_updated(self): - """ - :returns: Date this resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] +class ApplicationList(ListResource): - @property - def friendly_name(self): + def __init__(self, version: Version, account_sid: str): """ - :returns: Human readable description of this resource - :rtype: unicode - """ - return self._properties['friendly_name'] + Initialize the ApplicationList - @property - def message_status_callback(self): - """ - :returns: URL to make requests to with status updates - :rtype: unicode - """ - return self._properties['message_status_callback'] + :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. - @property - def sid(self): - """ - :returns: A string that uniquely identifies this resource - :rtype: unicode """ - return self._properties['sid'] + super().__init__(version) - @property - def sms_fallback_method(self): - """ - :returns: HTTP method to use with sms_fallback_method - :rtype: unicode - """ - return self._properties['sms_fallback_method'] + # 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"}) - @property - def sms_fallback_url(self): - """ - :returns: Fallback URL if there's an error parsing TwiML - :rtype: unicode - """ - return self._properties['sms_fallback_url'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def sms_method(self): - """ - :returns: HTTP method to use with sms_url - :rtype: unicode - """ - return self._properties['sms_method'] + headers["Accept"] = "application/json" - @property - def sms_status_callback(self): - """ - :returns: URL Twilio with request with status updates - :rtype: unicode - """ - return self._properties['sms_status_callback'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def sms_url(self): - """ - :returns: URL Twilio will request when receiving an SMS - :rtype: unicode - """ - return self._properties['sms_url'] + return ApplicationInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def status_callback(self): - """ - :returns: URL to hit with status updates - :rtype: unicode - """ - return self._properties['status_callback'] + 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"}) - @property - def status_callback_method(self): - """ - :returns: HTTP method to use with the status callback - :rtype: unicode - """ - return self._properties['status_callback_method'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def uri(self): + 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]: """ - :returns: URI for this resource - :rtype: unicode + 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 """ - return self._properties['uri'] + limits = self._version.read_limits(limit, page_size) + page = self.page(friendly_name=friendly_name, page_size=limits["page_size"]) - @property - def voice_caller_id_lookup(self): + 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]: """ - :returns: True or False - :rtype: bool + 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 """ - return self._properties['voice_caller_id_lookup'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) - @property - def voice_fallback_method(self): + 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]: """ - :returns: HTTP method to use with the fallback url - :rtype: unicode + 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]: """ - return self._properties['voice_fallback_method'] + 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. - @property - def voice_fallback_url(self): + :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: """ - :returns: Fallback URL - :rtype: unicode + 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 """ - return self._properties['voice_fallback_url'] + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def voice_method(self): + headers = values.of({"Content-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: """ - :returns: HTTP method to use with the URL - :rtype: unicode + 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 """ - return self._properties['voice_method'] + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def voice_url(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: URL Twilio will make requests to when relieving a call - :rtype: unicode + 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 """ - return self._properties['voice_url'] + response = self._version.domain.twilio.request("GET", target_url) + return ApplicationPage(self._version, response, self._solution) - def delete(self): + async def get_page_async(self, target_url: str) -> ApplicationPage: """ - Deletes the ApplicationInstance + Asynchronously retrieve a specific page of ApplicationInstance records from the API. + Request is executed immediately - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param target_url: API-generated URL for the requested results page + + :returns: Page of ApplicationInstance """ - return self._proxy.delete() + response = await self._version.domain.twilio.request_async("GET", target_url) + return ApplicationPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> ApplicationContext: """ - Fetch a ApplicationInstance + Constructs a ApplicationContext - :returns: Fetched ApplicationInstance - :rtype: twilio.rest.api.v2010.account.application.ApplicationInstance + :param sid: The Twilio-provided string that uniquely identifies the Application resource to update. """ - return self._proxy.fetch() + return ApplicationContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def update(self, friendly_name=values.unset, api_version=values.unset, - voice_url=values.unset, voice_method=values.unset, - voice_fallback_url=values.unset, voice_fallback_method=values.unset, - status_callback=values.unset, status_callback_method=values.unset, - voice_caller_id_lookup=values.unset, sms_url=values.unset, - sms_method=values.unset, sms_fallback_url=values.unset, - sms_fallback_method=values.unset, sms_status_callback=values.unset, - message_status_callback=values.unset): + def __call__(self, sid: str) -> ApplicationContext: """ - Update the ApplicationInstance + Constructs a ApplicationContext - :param unicode friendly_name: Human readable description of this resource - :param unicode api_version: The API version to use - :param unicode voice_url: URL Twilio will make requests to when relieving a call - :param unicode voice_method: HTTP method to use with the URL - :param unicode voice_fallback_url: Fallback URL - :param unicode voice_fallback_method: HTTP method to use with the fallback url - :param unicode status_callback: URL to hit with status updates - :param unicode status_callback_method: HTTP method to use with the status callback - :param bool voice_caller_id_lookup: True or False - :param unicode sms_url: URL Twilio will request when receiving an SMS - :param unicode sms_method: HTTP method to use with sms_url - :param unicode sms_fallback_url: Fallback URL if there's an error parsing TwiML - :param unicode sms_fallback_method: HTTP method to use with sms_fallback_method - :param unicode sms_status_callback: URL Twilio with request with status updates - :param unicode message_status_callback: URL to make requests to with status updates - - :returns: Updated ApplicationInstance - :rtype: twilio.rest.api.v2010.account.application.ApplicationInstance + :param sid: The Twilio-provided string that uniquely identifies the Application resource to update. """ - 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, + return ApplicationContext( + self._version, account_sid=self._solution["account_sid"], sid=sid ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/api/v2010/account/authorized_connect_app.py b/twilio/rest/api/v2010/account/authorized_connect_app.py index 4daf004c2b..cceb694c10 100644 --- a/twilio/rest/api/v2010/account/authorized_connect_app.py +++ b/twilio/rest/api/v2010/account/authorized_connect_app.py @@ -1,405 +1,458 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize +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 AuthorizedConnectAppList(ListResource): - """ """ +class AuthorizedConnectAppInstance(InstanceResource): - def __init__(self, version, account_sid): - """ - Initialize the AuthorizedConnectAppList + class Permission(object): + GET_ALL = "get-all" + POST_ALL = "post-all" - :param Version version: Version that contains the resource - :param account_sid: The unique sid that identifies this account + """ + :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") - :returns: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppList - :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppList + 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": """ - super(AuthorizedConnectAppList, self).__init__(version) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/AuthorizedConnectApps.json'.format(**self._solution) + :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 stream(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the AuthorizedConnectAppInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppInstance] + :returns: The fetched AuthorizedConnectAppInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(page_size=limits['page_size'], ) + async def fetch_async(self) -> "AuthorizedConnectAppInstance": + """ + Asynchronous coroutine to fetch the AuthorizedConnectAppInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + return await self._proxy.fetch_async() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppInstance] + def __repr__(self) -> str: """ - return list(self.stream(limit=limit, page_size=page_size, )) + Provide a friendly representation - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + :returns: Machine friendly representation """ - Retrieve a single page of AuthorizedConnectAppInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of AuthorizedConnectAppInstance - :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppPage +class AuthorizedConnectAppContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, connect_app_sid: str): """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the AuthorizedConnectAppContext - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + :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) - return AuthorizedConnectAppPage(self._version, response, self._solution) + # 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 get_page(self, target_url): + def fetch(self) -> AuthorizedConnectAppInstance: """ - Retrieve a specific page of AuthorizedConnectAppInstance records from the API. - Request is executed immediately + Fetch the AuthorizedConnectAppInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of AuthorizedConnectAppInstance - :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppPage + :returns: The fetched AuthorizedConnectAppInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return AuthorizedConnectAppPage(self._version, response, self._solution) + headers = values.of({}) - def get(self, connect_app_sid): - """ - Constructs a AuthorizedConnectAppContext + headers["Accept"] = "application/json" - :param connect_app_sid: The connect_app_sid + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppContext - :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppContext - """ - return AuthorizedConnectAppContext( + return AuthorizedConnectAppInstance( self._version, - account_sid=self._solution['account_sid'], - connect_app_sid=connect_app_sid, + payload, + account_sid=self._solution["account_sid"], + connect_app_sid=self._solution["connect_app_sid"], ) - def __call__(self, connect_app_sid): + async def fetch_async(self) -> AuthorizedConnectAppInstance: """ - Constructs a AuthorizedConnectAppContext + Asynchronous coroutine to fetch the AuthorizedConnectAppInstance - :param connect_app_sid: The connect_app_sid - :returns: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppContext - :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppContext + :returns: The fetched AuthorizedConnectAppInstance """ - return AuthorizedConnectAppContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AuthorizedConnectAppInstance( self._version, - account_sid=self._solution['account_sid'], - connect_app_sid=connect_app_sid, + payload, + account_sid=self._solution["account_sid"], + connect_app_sid=self._solution["connect_app_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) class AuthorizedConnectAppPage(Page): - """ """ - def __init__(self, version, response, solution): - """ - Initialize the AuthorizedConnectAppPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The unique sid that identifies this account - - :returns: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppPage - :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppPage - """ - super(AuthorizedConnectAppPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): + def get_instance(self, payload: Dict[str, Any]) -> AuthorizedConnectAppInstance: """ Build an instance of AuthorizedConnectAppInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppInstance - :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppInstance + :param payload: Payload response from the API """ return AuthorizedConnectAppInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], + self._version, payload, account_sid=self._solution["account_sid"] ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class AuthorizedConnectAppContext(InstanceContext): - """ """ +class AuthorizedConnectAppList(ListResource): - def __init__(self, version, account_sid, connect_app_sid): + def __init__(self, version: Version, account_sid: str): """ - Initialize the AuthorizedConnectAppContext + Initialize the AuthorizedConnectAppList - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param connect_app_sid: The connect_app_sid + :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. - :returns: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppContext - :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppContext """ - super(AuthorizedConnectAppContext, self).__init__(version) + 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) + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/AuthorizedConnectApps.json".format( + **self._solution + ) - def fetch(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AuthorizedConnectAppInstance]: """ - Fetch a 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. - :returns: Fetched AuthorizedConnectAppInstance - :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppInstance - """ - params = values.of({}) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) + :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 AuthorizedConnectAppInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - connect_app_sid=self._solution['connect_app_sid'], - ) + return self._version.stream(page, limits["limit"]) - def __repr__(self): + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AuthorizedConnectAppInstance]: """ - Provide a friendly representation + 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. - :returns: Machine friendly representation - :rtype: str + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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"]) -class AuthorizedConnectAppInstance(InstanceResource): - """ """ + 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. - class Permission(object): - GET_ALL = "get-all" - POST_ALL = "post-all" + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - def __init__(self, version, payload, account_sid, connect_app_sid=None): + :returns: list that will contain up to limit results """ - Initialize the AuthorizedConnectAppInstance + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - :returns: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppInstance - :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppInstance + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthorizedConnectAppInstance]: """ - super(AuthorizedConnectAppInstance, self).__init__(version) + 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. - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'connect_app_company_name': payload['connect_app_company_name'], - 'connect_app_description': payload['connect_app_description'], - 'connect_app_friendly_name': payload['connect_app_friendly_name'], - 'connect_app_homepage_url': payload['connect_app_homepage_url'], - 'connect_app_sid': payload['connect_app_sid'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'permissions': payload['permissions'], - 'uri': payload['uri'], - } + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - # Context - self._context = None - self._solution = { - 'account_sid': account_sid, - 'connect_app_sid': connect_app_sid or self._properties['connect_app_sid'], - } - - @property - def _proxy(self): + :returns: list that will contain up to limit results """ - 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 - :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppContext - """ - 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 [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, ) - return self._context + ] - @property - def account_sid(self): + 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: """ - :returns: The unique sid that identifies this account - :rtype: unicode - """ - return self._properties['account_sid'] + Retrieve a single page of AuthorizedConnectAppInstance records from the API. + Request is executed immediately - @property - def connect_app_company_name(self): - """ - :returns: The company name set for this Connect App. - :rtype: unicode - """ - return self._properties['connect_app_company_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 - @property - def connect_app_description(self): - """ - :returns: Human readable description of the app - :rtype: unicode + :returns: Page of AuthorizedConnectAppInstance """ - return self._properties['connect_app_description'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def connect_app_friendly_name(self): - """ - :returns: A human readable name for the Connect App. - :rtype: unicode - """ - return self._properties['connect_app_friendly_name'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def connect_app_homepage_url(self): - """ - :returns: The public URL for this Connect App. - :rtype: unicode - """ - return self._properties['connect_app_homepage_url'] + headers["Accept"] = "application/json" - @property - def connect_app_sid(self): - """ - :returns: A string that uniquely identifies this app - :rtype: unicode - """ - return self._properties['connect_app_sid'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthorizedConnectAppPage(self._version, response, self._solution) - @property - def date_created(self): + 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: """ - :returns: The date this resource was created - :rtype: datetime + 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 """ - return self._properties['date_created'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def date_updated(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The date this resource was last updated - :rtype: datetime + 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 """ - return self._properties['date_updated'] + response = self._version.domain.twilio.request("GET", target_url) + return AuthorizedConnectAppPage(self._version, response, self._solution) - @property - def permissions(self): + async def get_page_async(self, target_url: str) -> AuthorizedConnectAppPage: """ - :returns: Permissions authorized to this app - :rtype: AuthorizedConnectAppInstance.Permission + 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 """ - return self._properties['permissions'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return AuthorizedConnectAppPage(self._version, response, self._solution) - @property - def uri(self): + def get(self, connect_app_sid: str) -> AuthorizedConnectAppContext: """ - :returns: The URI for this resource - :rtype: unicode + Constructs a AuthorizedConnectAppContext + + :param connect_app_sid: The SID of the Connect App to fetch. """ - return self._properties['uri'] + return AuthorizedConnectAppContext( + self._version, + account_sid=self._solution["account_sid"], + connect_app_sid=connect_app_sid, + ) - def fetch(self): + def __call__(self, connect_app_sid: str) -> AuthorizedConnectAppContext: """ - Fetch a AuthorizedConnectAppInstance + Constructs a AuthorizedConnectAppContext - :returns: Fetched AuthorizedConnectAppInstance - :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppInstance + :param connect_app_sid: The SID of the Connect App to fetch. """ - return self._proxy.fetch() + return AuthorizedConnectAppContext( + self._version, + account_sid=self._solution["account_sid"], + connect_app_sid=connect_app_sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/api/v2010/account/available_phone_number/__init__.py b/twilio/rest/api/v2010/account/available_phone_number/__init__.py deleted file mode 100644 index ad4c449179..0000000000 --- a/twilio/rest/api/v2010/account/available_phone_number/__init__.py +++ /dev/null @@ -1,553 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -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.page import Page -from twilio.rest.api.v2010.account.available_phone_number.local import LocalList -from twilio.rest.api.v2010.account.available_phone_number.machine_to_machine import MachineToMachineList -from twilio.rest.api.v2010.account.available_phone_number.mobile import MobileList -from twilio.rest.api.v2010.account.available_phone_number.national import NationalList -from twilio.rest.api.v2010.account.available_phone_number.shared_cost import SharedCostList -from twilio.rest.api.v2010.account.available_phone_number.toll_free import TollFreeList -from twilio.rest.api.v2010.account.available_phone_number.voip import VoipList - - -class AvailablePhoneNumberCountryList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the AvailablePhoneNumberCountryList - - :param Version version: Version that contains the resource - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryList - :rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryList - """ - super(AvailablePhoneNumberCountryList, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/AvailablePhoneNumbers.json'.format(**self._solution) - - def stream(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of AvailablePhoneNumberCountryInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of AvailablePhoneNumberCountryInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryPage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return AvailablePhoneNumberCountryPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of AvailablePhoneNumberCountryInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of AvailablePhoneNumberCountryInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return AvailablePhoneNumberCountryPage(self._version, response, self._solution) - - def get(self, country_code): - """ - Constructs a AvailablePhoneNumberCountryContext - - :param country_code: The country_code - - :returns: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryContext - :rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryContext - """ - return AvailablePhoneNumberCountryContext( - self._version, - account_sid=self._solution['account_sid'], - country_code=country_code, - ) - - def __call__(self, country_code): - """ - Constructs a AvailablePhoneNumberCountryContext - - :param country_code: The country_code - - :returns: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryContext - :rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryContext - """ - return AvailablePhoneNumberCountryContext( - self._version, - account_sid=self._solution['account_sid'], - country_code=country_code, - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class AvailablePhoneNumberCountryPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the AvailablePhoneNumberCountryPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryPage - :rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryPage - """ - super(AvailablePhoneNumberCountryPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of AvailablePhoneNumberCountryInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryInstance - """ - return AvailablePhoneNumberCountryInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class AvailablePhoneNumberCountryContext(InstanceContext): - """ """ - - def __init__(self, version, account_sid, country_code): - """ - Initialize the AvailablePhoneNumberCountryContext - - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param country_code: The country_code - - :returns: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryContext - :rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryContext - """ - super(AvailablePhoneNumberCountryContext, self).__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) - - # Dependents - self._local = None - self._toll_free = None - self._mobile = None - self._national = None - self._voip = None - self._shared_cost = None - self._machine_to_machine = None - - def fetch(self): - """ - Fetch a AvailablePhoneNumberCountryInstance - - :returns: Fetched AvailablePhoneNumberCountryInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return AvailablePhoneNumberCountryInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - country_code=self._solution['country_code'], - ) - - @property - def local(self): - """ - Access the local - - :returns: twilio.rest.api.v2010.account.available_phone_number.local.LocalList - :rtype: twilio.rest.api.v2010.account.available_phone_number.local.LocalList - """ - if self._local is None: - self._local = LocalList( - self._version, - account_sid=self._solution['account_sid'], - country_code=self._solution['country_code'], - ) - return self._local - - @property - def toll_free(self): - """ - Access the toll_free - - :returns: twilio.rest.api.v2010.account.available_phone_number.toll_free.TollFreeList - :rtype: twilio.rest.api.v2010.account.available_phone_number.toll_free.TollFreeList - """ - if self._toll_free is None: - self._toll_free = TollFreeList( - self._version, - account_sid=self._solution['account_sid'], - country_code=self._solution['country_code'], - ) - return self._toll_free - - @property - def mobile(self): - """ - Access the mobile - - :returns: twilio.rest.api.v2010.account.available_phone_number.mobile.MobileList - :rtype: twilio.rest.api.v2010.account.available_phone_number.mobile.MobileList - """ - if self._mobile is None: - self._mobile = MobileList( - self._version, - account_sid=self._solution['account_sid'], - country_code=self._solution['country_code'], - ) - return self._mobile - - @property - def national(self): - """ - Access the national - - :returns: twilio.rest.api.v2010.account.available_phone_number.national.NationalList - :rtype: twilio.rest.api.v2010.account.available_phone_number.national.NationalList - """ - if self._national is None: - self._national = NationalList( - self._version, - account_sid=self._solution['account_sid'], - country_code=self._solution['country_code'], - ) - return self._national - - @property - def voip(self): - """ - Access the voip - - :returns: twilio.rest.api.v2010.account.available_phone_number.voip.VoipList - :rtype: twilio.rest.api.v2010.account.available_phone_number.voip.VoipList - """ - if self._voip is None: - self._voip = VoipList( - self._version, - account_sid=self._solution['account_sid'], - country_code=self._solution['country_code'], - ) - return self._voip - - @property - def shared_cost(self): - """ - Access the shared_cost - - :returns: twilio.rest.api.v2010.account.available_phone_number.shared_cost.SharedCostList - :rtype: twilio.rest.api.v2010.account.available_phone_number.shared_cost.SharedCostList - """ - if self._shared_cost is None: - self._shared_cost = SharedCostList( - self._version, - account_sid=self._solution['account_sid'], - country_code=self._solution['country_code'], - ) - return self._shared_cost - - @property - def machine_to_machine(self): - """ - Access the machine_to_machine - - :returns: twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToMachineList - :rtype: twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToMachineList - """ - if self._machine_to_machine is None: - self._machine_to_machine = MachineToMachineList( - self._version, - account_sid=self._solution['account_sid'], - country_code=self._solution['country_code'], - ) - return self._machine_to_machine - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class AvailablePhoneNumberCountryInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid, country_code=None): - """ - Initialize the AvailablePhoneNumberCountryInstance - - :returns: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryInstance - """ - super(AvailablePhoneNumberCountryInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'country_code': payload['country_code'], - 'country': payload['country'], - 'uri': payload['uri'], - 'beta': payload['beta'], - 'subresource_uris': payload['subresource_uris'], - } - - # Context - self._context = None - self._solution = { - 'account_sid': account_sid, - 'country_code': country_code or self._properties['country_code'], - } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryContext - """ - 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 - - @property - def country_code(self): - """ - :returns: The ISO Country code to lookup phone numbers for. - :rtype: unicode - """ - return self._properties['country_code'] - - @property - def country(self): - """ - :returns: The country - :rtype: unicode - """ - return self._properties['country'] - - @property - def uri(self): - """ - :returns: The uri - :rtype: unicode - """ - return self._properties['uri'] - - @property - def beta(self): - """ - :returns: The beta - :rtype: bool - """ - return self._properties['beta'] - - @property - def subresource_uris(self): - """ - :returns: The subresource_uris - :rtype: unicode - """ - return self._properties['subresource_uris'] - - def fetch(self): - """ - Fetch a AvailablePhoneNumberCountryInstance - - :returns: Fetched AvailablePhoneNumberCountryInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryInstance - """ - return self._proxy.fetch() - - @property - def local(self): - """ - Access the local - - :returns: twilio.rest.api.v2010.account.available_phone_number.local.LocalList - :rtype: twilio.rest.api.v2010.account.available_phone_number.local.LocalList - """ - return self._proxy.local - - @property - def toll_free(self): - """ - Access the toll_free - - :returns: twilio.rest.api.v2010.account.available_phone_number.toll_free.TollFreeList - :rtype: twilio.rest.api.v2010.account.available_phone_number.toll_free.TollFreeList - """ - return self._proxy.toll_free - - @property - def mobile(self): - """ - Access the mobile - - :returns: twilio.rest.api.v2010.account.available_phone_number.mobile.MobileList - :rtype: twilio.rest.api.v2010.account.available_phone_number.mobile.MobileList - """ - return self._proxy.mobile - - @property - def national(self): - """ - Access the national - - :returns: twilio.rest.api.v2010.account.available_phone_number.national.NationalList - :rtype: twilio.rest.api.v2010.account.available_phone_number.national.NationalList - """ - return self._proxy.national - - @property - def voip(self): - """ - Access the voip - - :returns: twilio.rest.api.v2010.account.available_phone_number.voip.VoipList - :rtype: twilio.rest.api.v2010.account.available_phone_number.voip.VoipList - """ - return self._proxy.voip - - @property - def shared_cost(self): - """ - Access the shared_cost - - :returns: twilio.rest.api.v2010.account.available_phone_number.shared_cost.SharedCostList - :rtype: twilio.rest.api.v2010.account.available_phone_number.shared_cost.SharedCostList - """ - return self._proxy.shared_cost - - @property - def machine_to_machine(self): - """ - Access the machine_to_machine - - :returns: twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToMachineList - :rtype: twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToMachineList - """ - return self._proxy.machine_to_machine - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/api/v2010/account/available_phone_number/local.py b/twilio/rest/api/v2010/account/available_phone_number/local.py deleted file mode 100644 index 615ccb4899..0000000000 --- a/twilio/rest/api/v2010/account/available_phone_number/local.py +++ /dev/null @@ -1,462 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import values -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.page import Page - - -class LocalList(ListResource): - """ """ - - def __init__(self, version, account_sid, country_code): - """ - Initialize the LocalList - - :param Version version: Version that contains the resource - :param account_sid: The 34 character string that uniquely identifies your account. - :param country_code: The ISO Country code to lookup phone numbers for. - - :returns: twilio.rest.api.v2010.account.available_phone_number.local.LocalList - :rtype: twilio.rest.api.v2010.account.available_phone_number.local.LocalList - """ - super(LocalList, self).__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=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, - exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, limit=None, page_size=None): - """ - 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 unicode area_code: The area_code - :param unicode contains: The contains - :param bool sms_enabled: The sms_enabled - :param bool mms_enabled: The mms_enabled - :param bool voice_enabled: The voice_enabled - :param bool exclude_all_address_required: The exclude_all_address_required - :param bool exclude_local_address_required: The exclude_local_address_required - :param bool exclude_foreign_address_required: The exclude_foreign_address_required - :param bool beta: The beta - :param unicode near_number: The near_number - :param unicode near_lat_long: The near_lat_long - :param unicode distance: The distance - :param unicode in_postal_code: The in_postal_code - :param unicode in_region: The in_region - :param unicode in_rate_center: The in_rate_center - :param unicode in_lata: The in_lata - :param unicode in_locality: The in_locality - :param bool fax_enabled: The fax_enabled - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.available_phone_number.local.LocalInstance] - """ - 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'], limits['page_limit']) - - def list(self, area_code=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, limit=None, page_size=None): - """ - 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 unicode area_code: The area_code - :param unicode contains: The contains - :param bool sms_enabled: The sms_enabled - :param bool mms_enabled: The mms_enabled - :param bool voice_enabled: The voice_enabled - :param bool exclude_all_address_required: The exclude_all_address_required - :param bool exclude_local_address_required: The exclude_local_address_required - :param bool exclude_foreign_address_required: The exclude_foreign_address_required - :param bool beta: The beta - :param unicode near_number: The near_number - :param unicode near_lat_long: The near_lat_long - :param unicode distance: The distance - :param unicode in_postal_code: The in_postal_code - :param unicode in_region: The in_region - :param unicode in_rate_center: The in_rate_center - :param unicode in_lata: The in_lata - :param unicode in_locality: The in_locality - :param bool fax_enabled: The fax_enabled - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.available_phone_number.local.LocalInstance] - """ - 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, - )) - - def page(self, area_code=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of LocalInstance records from the API. - Request is executed immediately - - :param unicode area_code: The area_code - :param unicode contains: The contains - :param bool sms_enabled: The sms_enabled - :param bool mms_enabled: The mms_enabled - :param bool voice_enabled: The voice_enabled - :param bool exclude_all_address_required: The exclude_all_address_required - :param bool exclude_local_address_required: The exclude_local_address_required - :param bool exclude_foreign_address_required: The exclude_foreign_address_required - :param bool beta: The beta - :param unicode near_number: The near_number - :param unicode near_lat_long: The near_lat_long - :param unicode distance: The distance - :param unicode in_postal_code: The in_postal_code - :param unicode in_region: The in_region - :param unicode in_rate_center: The in_rate_center - :param unicode in_lata: The in_lata - :param unicode in_locality: The in_locality - :param bool fax_enabled: The fax_enabled - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of LocalInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.local.LocalPage - """ - params = values.of({ - 'AreaCode': area_code, - 'Contains': contains, - 'SmsEnabled': sms_enabled, - 'MmsEnabled': mms_enabled, - 'VoiceEnabled': voice_enabled, - 'ExcludeAllAddressRequired': exclude_all_address_required, - 'ExcludeLocalAddressRequired': exclude_local_address_required, - 'ExcludeForeignAddressRequired': exclude_foreign_address_required, - 'Beta': 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': fax_enabled, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return LocalPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of LocalInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of LocalInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.local.LocalPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return LocalPage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class LocalPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the LocalPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The 34 character string that uniquely identifies your account. - :param country_code: The ISO Country code to lookup phone numbers for. - - :returns: twilio.rest.api.v2010.account.available_phone_number.local.LocalPage - :rtype: twilio.rest.api.v2010.account.available_phone_number.local.LocalPage - """ - super(LocalPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of LocalInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.available_phone_number.local.LocalInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.local.LocalInstance - """ - return LocalInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - country_code=self._solution['country_code'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class LocalInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid, country_code): - """ - Initialize the LocalInstance - - :returns: twilio.rest.api.v2010.account.available_phone_number.local.LocalInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.local.LocalInstance - """ - super(LocalInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'friendly_name': payload['friendly_name'], - 'phone_number': payload['phone_number'], - 'lata': payload['lata'], - 'locality': payload['locality'], - 'rate_center': payload['rate_center'], - 'latitude': deserialize.decimal(payload['latitude']), - 'longitude': deserialize.decimal(payload['longitude']), - 'region': payload['region'], - 'postal_code': payload['postal_code'], - 'iso_country': payload['iso_country'], - 'address_requirements': payload['address_requirements'], - 'beta': payload['beta'], - 'capabilities': payload['capabilities'], - } - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'country_code': country_code, } - - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def phone_number(self): - """ - :returns: The phone_number - :rtype: unicode - """ - return self._properties['phone_number'] - - @property - def lata(self): - """ - :returns: The lata - :rtype: unicode - """ - return self._properties['lata'] - - @property - def locality(self): - """ - :returns: The locality - :rtype: unicode - """ - return self._properties['locality'] - - @property - def rate_center(self): - """ - :returns: The rate_center - :rtype: unicode - """ - return self._properties['rate_center'] - - @property - def latitude(self): - """ - :returns: The latitude - :rtype: unicode - """ - return self._properties['latitude'] - - @property - def longitude(self): - """ - :returns: The longitude - :rtype: unicode - """ - return self._properties['longitude'] - - @property - def region(self): - """ - :returns: The region - :rtype: unicode - """ - return self._properties['region'] - - @property - def postal_code(self): - """ - :returns: The postal_code - :rtype: unicode - """ - return self._properties['postal_code'] - - @property - def iso_country(self): - """ - :returns: The iso_country - :rtype: unicode - """ - return self._properties['iso_country'] - - @property - def address_requirements(self): - """ - :returns: The address_requirements - :rtype: unicode - """ - return self._properties['address_requirements'] - - @property - def beta(self): - """ - :returns: The beta - :rtype: bool - """ - return self._properties['beta'] - - @property - def capabilities(self): - """ - :returns: The capabilities - :rtype: unicode - """ - return self._properties['capabilities'] - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/api/v2010/account/available_phone_number/machine_to_machine.py b/twilio/rest/api/v2010/account/available_phone_number/machine_to_machine.py deleted file mode 100644 index 74fe5e1ce9..0000000000 --- a/twilio/rest/api/v2010/account/available_phone_number/machine_to_machine.py +++ /dev/null @@ -1,462 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import values -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.page import Page - - -class MachineToMachineList(ListResource): - """ """ - - def __init__(self, version, account_sid, country_code): - """ - Initialize the MachineToMachineList - - :param Version version: Version that contains the resource - :param account_sid: The 34 character string that uniquely identifies your account. - :param country_code: The ISO Country code to lookup phone numbers for. - - :returns: twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToMachineList - :rtype: twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToMachineList - """ - super(MachineToMachineList, self).__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=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, - exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, limit=None, page_size=None): - """ - 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 unicode area_code: The area_code - :param unicode contains: The contains - :param bool sms_enabled: The sms_enabled - :param bool mms_enabled: The mms_enabled - :param bool voice_enabled: The voice_enabled - :param bool exclude_all_address_required: The exclude_all_address_required - :param bool exclude_local_address_required: The exclude_local_address_required - :param bool exclude_foreign_address_required: The exclude_foreign_address_required - :param bool beta: The beta - :param unicode near_number: The near_number - :param unicode near_lat_long: The near_lat_long - :param unicode distance: The distance - :param unicode in_postal_code: The in_postal_code - :param unicode in_region: The in_region - :param unicode in_rate_center: The in_rate_center - :param unicode in_lata: The in_lata - :param unicode in_locality: The in_locality - :param bool fax_enabled: The fax_enabled - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToMachineInstance] - """ - 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'], limits['page_limit']) - - def list(self, area_code=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, limit=None, page_size=None): - """ - 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 unicode area_code: The area_code - :param unicode contains: The contains - :param bool sms_enabled: The sms_enabled - :param bool mms_enabled: The mms_enabled - :param bool voice_enabled: The voice_enabled - :param bool exclude_all_address_required: The exclude_all_address_required - :param bool exclude_local_address_required: The exclude_local_address_required - :param bool exclude_foreign_address_required: The exclude_foreign_address_required - :param bool beta: The beta - :param unicode near_number: The near_number - :param unicode near_lat_long: The near_lat_long - :param unicode distance: The distance - :param unicode in_postal_code: The in_postal_code - :param unicode in_region: The in_region - :param unicode in_rate_center: The in_rate_center - :param unicode in_lata: The in_lata - :param unicode in_locality: The in_locality - :param bool fax_enabled: The fax_enabled - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToMachineInstance] - """ - 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, - )) - - def page(self, area_code=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of MachineToMachineInstance records from the API. - Request is executed immediately - - :param unicode area_code: The area_code - :param unicode contains: The contains - :param bool sms_enabled: The sms_enabled - :param bool mms_enabled: The mms_enabled - :param bool voice_enabled: The voice_enabled - :param bool exclude_all_address_required: The exclude_all_address_required - :param bool exclude_local_address_required: The exclude_local_address_required - :param bool exclude_foreign_address_required: The exclude_foreign_address_required - :param bool beta: The beta - :param unicode near_number: The near_number - :param unicode near_lat_long: The near_lat_long - :param unicode distance: The distance - :param unicode in_postal_code: The in_postal_code - :param unicode in_region: The in_region - :param unicode in_rate_center: The in_rate_center - :param unicode in_lata: The in_lata - :param unicode in_locality: The in_locality - :param bool fax_enabled: The fax_enabled - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of MachineToMachineInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToMachinePage - """ - params = values.of({ - 'AreaCode': area_code, - 'Contains': contains, - 'SmsEnabled': sms_enabled, - 'MmsEnabled': mms_enabled, - 'VoiceEnabled': voice_enabled, - 'ExcludeAllAddressRequired': exclude_all_address_required, - 'ExcludeLocalAddressRequired': exclude_local_address_required, - 'ExcludeForeignAddressRequired': exclude_foreign_address_required, - 'Beta': 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': fax_enabled, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return MachineToMachinePage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of MachineToMachineInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of MachineToMachineInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToMachinePage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return MachineToMachinePage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class MachineToMachinePage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the MachineToMachinePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The 34 character string that uniquely identifies your account. - :param country_code: The ISO Country code to lookup phone numbers for. - - :returns: twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToMachinePage - :rtype: twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToMachinePage - """ - super(MachineToMachinePage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of MachineToMachineInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToMachineInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToMachineInstance - """ - return MachineToMachineInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - country_code=self._solution['country_code'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class MachineToMachineInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid, country_code): - """ - Initialize the MachineToMachineInstance - - :returns: twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToMachineInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToMachineInstance - """ - super(MachineToMachineInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'friendly_name': payload['friendly_name'], - 'phone_number': payload['phone_number'], - 'lata': payload['lata'], - 'locality': payload['locality'], - 'rate_center': payload['rate_center'], - 'latitude': deserialize.decimal(payload['latitude']), - 'longitude': deserialize.decimal(payload['longitude']), - 'region': payload['region'], - 'postal_code': payload['postal_code'], - 'iso_country': payload['iso_country'], - 'address_requirements': payload['address_requirements'], - 'beta': payload['beta'], - 'capabilities': payload['capabilities'], - } - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'country_code': country_code, } - - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def phone_number(self): - """ - :returns: The phone_number - :rtype: unicode - """ - return self._properties['phone_number'] - - @property - def lata(self): - """ - :returns: The lata - :rtype: unicode - """ - return self._properties['lata'] - - @property - def locality(self): - """ - :returns: The locality - :rtype: unicode - """ - return self._properties['locality'] - - @property - def rate_center(self): - """ - :returns: The rate_center - :rtype: unicode - """ - return self._properties['rate_center'] - - @property - def latitude(self): - """ - :returns: The latitude - :rtype: unicode - """ - return self._properties['latitude'] - - @property - def longitude(self): - """ - :returns: The longitude - :rtype: unicode - """ - return self._properties['longitude'] - - @property - def region(self): - """ - :returns: The region - :rtype: unicode - """ - return self._properties['region'] - - @property - def postal_code(self): - """ - :returns: The postal_code - :rtype: unicode - """ - return self._properties['postal_code'] - - @property - def iso_country(self): - """ - :returns: The iso_country - :rtype: unicode - """ - return self._properties['iso_country'] - - @property - def address_requirements(self): - """ - :returns: The address_requirements - :rtype: unicode - """ - return self._properties['address_requirements'] - - @property - def beta(self): - """ - :returns: The beta - :rtype: bool - """ - return self._properties['beta'] - - @property - def capabilities(self): - """ - :returns: The capabilities - :rtype: unicode - """ - return self._properties['capabilities'] - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/api/v2010/account/available_phone_number/mobile.py b/twilio/rest/api/v2010/account/available_phone_number/mobile.py deleted file mode 100644 index 8d25959c96..0000000000 --- a/twilio/rest/api/v2010/account/available_phone_number/mobile.py +++ /dev/null @@ -1,462 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import values -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.page import Page - - -class MobileList(ListResource): - """ """ - - def __init__(self, version, account_sid, country_code): - """ - Initialize the MobileList - - :param Version version: Version that contains the resource - :param account_sid: The 34 character string that uniquely identifies your account. - :param country_code: The ISO Country code to lookup phone numbers for. - - :returns: twilio.rest.api.v2010.account.available_phone_number.mobile.MobileList - :rtype: twilio.rest.api.v2010.account.available_phone_number.mobile.MobileList - """ - super(MobileList, self).__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=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, - exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, limit=None, page_size=None): - """ - 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 unicode area_code: The area_code - :param unicode contains: The contains - :param bool sms_enabled: The sms_enabled - :param bool mms_enabled: The mms_enabled - :param bool voice_enabled: The voice_enabled - :param bool exclude_all_address_required: The exclude_all_address_required - :param bool exclude_local_address_required: The exclude_local_address_required - :param bool exclude_foreign_address_required: The exclude_foreign_address_required - :param bool beta: The beta - :param unicode near_number: The near_number - :param unicode near_lat_long: The near_lat_long - :param unicode distance: The distance - :param unicode in_postal_code: The in_postal_code - :param unicode in_region: The in_region - :param unicode in_rate_center: The in_rate_center - :param unicode in_lata: The in_lata - :param unicode in_locality: The in_locality - :param bool fax_enabled: The fax_enabled - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.available_phone_number.mobile.MobileInstance] - """ - 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'], limits['page_limit']) - - def list(self, area_code=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, limit=None, page_size=None): - """ - 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 unicode area_code: The area_code - :param unicode contains: The contains - :param bool sms_enabled: The sms_enabled - :param bool mms_enabled: The mms_enabled - :param bool voice_enabled: The voice_enabled - :param bool exclude_all_address_required: The exclude_all_address_required - :param bool exclude_local_address_required: The exclude_local_address_required - :param bool exclude_foreign_address_required: The exclude_foreign_address_required - :param bool beta: The beta - :param unicode near_number: The near_number - :param unicode near_lat_long: The near_lat_long - :param unicode distance: The distance - :param unicode in_postal_code: The in_postal_code - :param unicode in_region: The in_region - :param unicode in_rate_center: The in_rate_center - :param unicode in_lata: The in_lata - :param unicode in_locality: The in_locality - :param bool fax_enabled: The fax_enabled - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.available_phone_number.mobile.MobileInstance] - """ - 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, - )) - - def page(self, area_code=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of MobileInstance records from the API. - Request is executed immediately - - :param unicode area_code: The area_code - :param unicode contains: The contains - :param bool sms_enabled: The sms_enabled - :param bool mms_enabled: The mms_enabled - :param bool voice_enabled: The voice_enabled - :param bool exclude_all_address_required: The exclude_all_address_required - :param bool exclude_local_address_required: The exclude_local_address_required - :param bool exclude_foreign_address_required: The exclude_foreign_address_required - :param bool beta: The beta - :param unicode near_number: The near_number - :param unicode near_lat_long: The near_lat_long - :param unicode distance: The distance - :param unicode in_postal_code: The in_postal_code - :param unicode in_region: The in_region - :param unicode in_rate_center: The in_rate_center - :param unicode in_lata: The in_lata - :param unicode in_locality: The in_locality - :param bool fax_enabled: The fax_enabled - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of MobileInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.mobile.MobilePage - """ - params = values.of({ - 'AreaCode': area_code, - 'Contains': contains, - 'SmsEnabled': sms_enabled, - 'MmsEnabled': mms_enabled, - 'VoiceEnabled': voice_enabled, - 'ExcludeAllAddressRequired': exclude_all_address_required, - 'ExcludeLocalAddressRequired': exclude_local_address_required, - 'ExcludeForeignAddressRequired': exclude_foreign_address_required, - 'Beta': 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': fax_enabled, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return MobilePage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of MobileInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of MobileInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.mobile.MobilePage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return MobilePage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class MobilePage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the MobilePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The 34 character string that uniquely identifies your account. - :param country_code: The ISO Country code to lookup phone numbers for. - - :returns: twilio.rest.api.v2010.account.available_phone_number.mobile.MobilePage - :rtype: twilio.rest.api.v2010.account.available_phone_number.mobile.MobilePage - """ - super(MobilePage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of MobileInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.available_phone_number.mobile.MobileInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.mobile.MobileInstance - """ - return MobileInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - country_code=self._solution['country_code'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class MobileInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid, country_code): - """ - Initialize the MobileInstance - - :returns: twilio.rest.api.v2010.account.available_phone_number.mobile.MobileInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.mobile.MobileInstance - """ - super(MobileInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'friendly_name': payload['friendly_name'], - 'phone_number': payload['phone_number'], - 'lata': payload['lata'], - 'locality': payload['locality'], - 'rate_center': payload['rate_center'], - 'latitude': deserialize.decimal(payload['latitude']), - 'longitude': deserialize.decimal(payload['longitude']), - 'region': payload['region'], - 'postal_code': payload['postal_code'], - 'iso_country': payload['iso_country'], - 'address_requirements': payload['address_requirements'], - 'beta': payload['beta'], - 'capabilities': payload['capabilities'], - } - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'country_code': country_code, } - - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def phone_number(self): - """ - :returns: The phone_number - :rtype: unicode - """ - return self._properties['phone_number'] - - @property - def lata(self): - """ - :returns: The lata - :rtype: unicode - """ - return self._properties['lata'] - - @property - def locality(self): - """ - :returns: The locality - :rtype: unicode - """ - return self._properties['locality'] - - @property - def rate_center(self): - """ - :returns: The rate_center - :rtype: unicode - """ - return self._properties['rate_center'] - - @property - def latitude(self): - """ - :returns: The latitude - :rtype: unicode - """ - return self._properties['latitude'] - - @property - def longitude(self): - """ - :returns: The longitude - :rtype: unicode - """ - return self._properties['longitude'] - - @property - def region(self): - """ - :returns: The region - :rtype: unicode - """ - return self._properties['region'] - - @property - def postal_code(self): - """ - :returns: The postal_code - :rtype: unicode - """ - return self._properties['postal_code'] - - @property - def iso_country(self): - """ - :returns: The iso_country - :rtype: unicode - """ - return self._properties['iso_country'] - - @property - def address_requirements(self): - """ - :returns: The address_requirements - :rtype: unicode - """ - return self._properties['address_requirements'] - - @property - def beta(self): - """ - :returns: The beta - :rtype: bool - """ - return self._properties['beta'] - - @property - def capabilities(self): - """ - :returns: The capabilities - :rtype: unicode - """ - return self._properties['capabilities'] - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/api/v2010/account/available_phone_number/national.py b/twilio/rest/api/v2010/account/available_phone_number/national.py deleted file mode 100644 index cb3e6ba67e..0000000000 --- a/twilio/rest/api/v2010/account/available_phone_number/national.py +++ /dev/null @@ -1,462 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import values -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.page import Page - - -class NationalList(ListResource): - """ """ - - def __init__(self, version, account_sid, country_code): - """ - Initialize the NationalList - - :param Version version: Version that contains the resource - :param account_sid: The 34 character string that uniquely identifies your account. - :param country_code: The ISO Country code to lookup phone numbers for. - - :returns: twilio.rest.api.v2010.account.available_phone_number.national.NationalList - :rtype: twilio.rest.api.v2010.account.available_phone_number.national.NationalList - """ - super(NationalList, self).__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=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, - exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, limit=None, page_size=None): - """ - 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 unicode area_code: The area_code - :param unicode contains: The contains - :param bool sms_enabled: The sms_enabled - :param bool mms_enabled: The mms_enabled - :param bool voice_enabled: The voice_enabled - :param bool exclude_all_address_required: The exclude_all_address_required - :param bool exclude_local_address_required: The exclude_local_address_required - :param bool exclude_foreign_address_required: The exclude_foreign_address_required - :param bool beta: The beta - :param unicode near_number: The near_number - :param unicode near_lat_long: The near_lat_long - :param unicode distance: The distance - :param unicode in_postal_code: The in_postal_code - :param unicode in_region: The in_region - :param unicode in_rate_center: The in_rate_center - :param unicode in_lata: The in_lata - :param unicode in_locality: The in_locality - :param bool fax_enabled: The fax_enabled - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.available_phone_number.national.NationalInstance] - """ - 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'], limits['page_limit']) - - def list(self, area_code=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, limit=None, page_size=None): - """ - 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 unicode area_code: The area_code - :param unicode contains: The contains - :param bool sms_enabled: The sms_enabled - :param bool mms_enabled: The mms_enabled - :param bool voice_enabled: The voice_enabled - :param bool exclude_all_address_required: The exclude_all_address_required - :param bool exclude_local_address_required: The exclude_local_address_required - :param bool exclude_foreign_address_required: The exclude_foreign_address_required - :param bool beta: The beta - :param unicode near_number: The near_number - :param unicode near_lat_long: The near_lat_long - :param unicode distance: The distance - :param unicode in_postal_code: The in_postal_code - :param unicode in_region: The in_region - :param unicode in_rate_center: The in_rate_center - :param unicode in_lata: The in_lata - :param unicode in_locality: The in_locality - :param bool fax_enabled: The fax_enabled - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.available_phone_number.national.NationalInstance] - """ - 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, - )) - - def page(self, area_code=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of NationalInstance records from the API. - Request is executed immediately - - :param unicode area_code: The area_code - :param unicode contains: The contains - :param bool sms_enabled: The sms_enabled - :param bool mms_enabled: The mms_enabled - :param bool voice_enabled: The voice_enabled - :param bool exclude_all_address_required: The exclude_all_address_required - :param bool exclude_local_address_required: The exclude_local_address_required - :param bool exclude_foreign_address_required: The exclude_foreign_address_required - :param bool beta: The beta - :param unicode near_number: The near_number - :param unicode near_lat_long: The near_lat_long - :param unicode distance: The distance - :param unicode in_postal_code: The in_postal_code - :param unicode in_region: The in_region - :param unicode in_rate_center: The in_rate_center - :param unicode in_lata: The in_lata - :param unicode in_locality: The in_locality - :param bool fax_enabled: The fax_enabled - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of NationalInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.national.NationalPage - """ - params = values.of({ - 'AreaCode': area_code, - 'Contains': contains, - 'SmsEnabled': sms_enabled, - 'MmsEnabled': mms_enabled, - 'VoiceEnabled': voice_enabled, - 'ExcludeAllAddressRequired': exclude_all_address_required, - 'ExcludeLocalAddressRequired': exclude_local_address_required, - 'ExcludeForeignAddressRequired': exclude_foreign_address_required, - 'Beta': 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': fax_enabled, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return NationalPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of NationalInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of NationalInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.national.NationalPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return NationalPage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class NationalPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the NationalPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The 34 character string that uniquely identifies your account. - :param country_code: The ISO Country code to lookup phone numbers for. - - :returns: twilio.rest.api.v2010.account.available_phone_number.national.NationalPage - :rtype: twilio.rest.api.v2010.account.available_phone_number.national.NationalPage - """ - super(NationalPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of NationalInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.available_phone_number.national.NationalInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.national.NationalInstance - """ - return NationalInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - country_code=self._solution['country_code'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class NationalInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid, country_code): - """ - Initialize the NationalInstance - - :returns: twilio.rest.api.v2010.account.available_phone_number.national.NationalInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.national.NationalInstance - """ - super(NationalInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'friendly_name': payload['friendly_name'], - 'phone_number': payload['phone_number'], - 'lata': payload['lata'], - 'locality': payload['locality'], - 'rate_center': payload['rate_center'], - 'latitude': deserialize.decimal(payload['latitude']), - 'longitude': deserialize.decimal(payload['longitude']), - 'region': payload['region'], - 'postal_code': payload['postal_code'], - 'iso_country': payload['iso_country'], - 'address_requirements': payload['address_requirements'], - 'beta': payload['beta'], - 'capabilities': payload['capabilities'], - } - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'country_code': country_code, } - - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def phone_number(self): - """ - :returns: The phone_number - :rtype: unicode - """ - return self._properties['phone_number'] - - @property - def lata(self): - """ - :returns: The lata - :rtype: unicode - """ - return self._properties['lata'] - - @property - def locality(self): - """ - :returns: The locality - :rtype: unicode - """ - return self._properties['locality'] - - @property - def rate_center(self): - """ - :returns: The rate_center - :rtype: unicode - """ - return self._properties['rate_center'] - - @property - def latitude(self): - """ - :returns: The latitude - :rtype: unicode - """ - return self._properties['latitude'] - - @property - def longitude(self): - """ - :returns: The longitude - :rtype: unicode - """ - return self._properties['longitude'] - - @property - def region(self): - """ - :returns: The region - :rtype: unicode - """ - return self._properties['region'] - - @property - def postal_code(self): - """ - :returns: The postal_code - :rtype: unicode - """ - return self._properties['postal_code'] - - @property - def iso_country(self): - """ - :returns: The iso_country - :rtype: unicode - """ - return self._properties['iso_country'] - - @property - def address_requirements(self): - """ - :returns: The address_requirements - :rtype: unicode - """ - return self._properties['address_requirements'] - - @property - def beta(self): - """ - :returns: The beta - :rtype: bool - """ - return self._properties['beta'] - - @property - def capabilities(self): - """ - :returns: The capabilities - :rtype: unicode - """ - return self._properties['capabilities'] - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/api/v2010/account/available_phone_number/shared_cost.py b/twilio/rest/api/v2010/account/available_phone_number/shared_cost.py deleted file mode 100644 index 8fb9bc5585..0000000000 --- a/twilio/rest/api/v2010/account/available_phone_number/shared_cost.py +++ /dev/null @@ -1,462 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import values -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.page import Page - - -class SharedCostList(ListResource): - """ """ - - def __init__(self, version, account_sid, country_code): - """ - Initialize the SharedCostList - - :param Version version: Version that contains the resource - :param account_sid: The 34 character string that uniquely identifies your account. - :param country_code: The ISO Country code to lookup phone numbers for. - - :returns: twilio.rest.api.v2010.account.available_phone_number.shared_cost.SharedCostList - :rtype: twilio.rest.api.v2010.account.available_phone_number.shared_cost.SharedCostList - """ - super(SharedCostList, self).__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=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, - exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, limit=None, page_size=None): - """ - 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 unicode area_code: The area_code - :param unicode contains: The contains - :param bool sms_enabled: The sms_enabled - :param bool mms_enabled: The mms_enabled - :param bool voice_enabled: The voice_enabled - :param bool exclude_all_address_required: The exclude_all_address_required - :param bool exclude_local_address_required: The exclude_local_address_required - :param bool exclude_foreign_address_required: The exclude_foreign_address_required - :param bool beta: The beta - :param unicode near_number: The near_number - :param unicode near_lat_long: The near_lat_long - :param unicode distance: The distance - :param unicode in_postal_code: The in_postal_code - :param unicode in_region: The in_region - :param unicode in_rate_center: The in_rate_center - :param unicode in_lata: The in_lata - :param unicode in_locality: The in_locality - :param bool fax_enabled: The fax_enabled - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.available_phone_number.shared_cost.SharedCostInstance] - """ - 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'], limits['page_limit']) - - def list(self, area_code=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, limit=None, page_size=None): - """ - 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 unicode area_code: The area_code - :param unicode contains: The contains - :param bool sms_enabled: The sms_enabled - :param bool mms_enabled: The mms_enabled - :param bool voice_enabled: The voice_enabled - :param bool exclude_all_address_required: The exclude_all_address_required - :param bool exclude_local_address_required: The exclude_local_address_required - :param bool exclude_foreign_address_required: The exclude_foreign_address_required - :param bool beta: The beta - :param unicode near_number: The near_number - :param unicode near_lat_long: The near_lat_long - :param unicode distance: The distance - :param unicode in_postal_code: The in_postal_code - :param unicode in_region: The in_region - :param unicode in_rate_center: The in_rate_center - :param unicode in_lata: The in_lata - :param unicode in_locality: The in_locality - :param bool fax_enabled: The fax_enabled - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.available_phone_number.shared_cost.SharedCostInstance] - """ - 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, - )) - - def page(self, area_code=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of SharedCostInstance records from the API. - Request is executed immediately - - :param unicode area_code: The area_code - :param unicode contains: The contains - :param bool sms_enabled: The sms_enabled - :param bool mms_enabled: The mms_enabled - :param bool voice_enabled: The voice_enabled - :param bool exclude_all_address_required: The exclude_all_address_required - :param bool exclude_local_address_required: The exclude_local_address_required - :param bool exclude_foreign_address_required: The exclude_foreign_address_required - :param bool beta: The beta - :param unicode near_number: The near_number - :param unicode near_lat_long: The near_lat_long - :param unicode distance: The distance - :param unicode in_postal_code: The in_postal_code - :param unicode in_region: The in_region - :param unicode in_rate_center: The in_rate_center - :param unicode in_lata: The in_lata - :param unicode in_locality: The in_locality - :param bool fax_enabled: The fax_enabled - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of SharedCostInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.shared_cost.SharedCostPage - """ - params = values.of({ - 'AreaCode': area_code, - 'Contains': contains, - 'SmsEnabled': sms_enabled, - 'MmsEnabled': mms_enabled, - 'VoiceEnabled': voice_enabled, - 'ExcludeAllAddressRequired': exclude_all_address_required, - 'ExcludeLocalAddressRequired': exclude_local_address_required, - 'ExcludeForeignAddressRequired': exclude_foreign_address_required, - 'Beta': 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': fax_enabled, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return SharedCostPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of SharedCostInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of SharedCostInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.shared_cost.SharedCostPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return SharedCostPage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SharedCostPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the SharedCostPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The 34 character string that uniquely identifies your account. - :param country_code: The ISO Country code to lookup phone numbers for. - - :returns: twilio.rest.api.v2010.account.available_phone_number.shared_cost.SharedCostPage - :rtype: twilio.rest.api.v2010.account.available_phone_number.shared_cost.SharedCostPage - """ - super(SharedCostPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of SharedCostInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.available_phone_number.shared_cost.SharedCostInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.shared_cost.SharedCostInstance - """ - return SharedCostInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - country_code=self._solution['country_code'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SharedCostInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid, country_code): - """ - Initialize the SharedCostInstance - - :returns: twilio.rest.api.v2010.account.available_phone_number.shared_cost.SharedCostInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.shared_cost.SharedCostInstance - """ - super(SharedCostInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'friendly_name': payload['friendly_name'], - 'phone_number': payload['phone_number'], - 'lata': payload['lata'], - 'locality': payload['locality'], - 'rate_center': payload['rate_center'], - 'latitude': deserialize.decimal(payload['latitude']), - 'longitude': deserialize.decimal(payload['longitude']), - 'region': payload['region'], - 'postal_code': payload['postal_code'], - 'iso_country': payload['iso_country'], - 'address_requirements': payload['address_requirements'], - 'beta': payload['beta'], - 'capabilities': payload['capabilities'], - } - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'country_code': country_code, } - - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def phone_number(self): - """ - :returns: The phone_number - :rtype: unicode - """ - return self._properties['phone_number'] - - @property - def lata(self): - """ - :returns: The lata - :rtype: unicode - """ - return self._properties['lata'] - - @property - def locality(self): - """ - :returns: The locality - :rtype: unicode - """ - return self._properties['locality'] - - @property - def rate_center(self): - """ - :returns: The rate_center - :rtype: unicode - """ - return self._properties['rate_center'] - - @property - def latitude(self): - """ - :returns: The latitude - :rtype: unicode - """ - return self._properties['latitude'] - - @property - def longitude(self): - """ - :returns: The longitude - :rtype: unicode - """ - return self._properties['longitude'] - - @property - def region(self): - """ - :returns: The region - :rtype: unicode - """ - return self._properties['region'] - - @property - def postal_code(self): - """ - :returns: The postal_code - :rtype: unicode - """ - return self._properties['postal_code'] - - @property - def iso_country(self): - """ - :returns: The iso_country - :rtype: unicode - """ - return self._properties['iso_country'] - - @property - def address_requirements(self): - """ - :returns: The address_requirements - :rtype: unicode - """ - return self._properties['address_requirements'] - - @property - def beta(self): - """ - :returns: The beta - :rtype: bool - """ - return self._properties['beta'] - - @property - def capabilities(self): - """ - :returns: The capabilities - :rtype: unicode - """ - return self._properties['capabilities'] - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/api/v2010/account/available_phone_number/toll_free.py b/twilio/rest/api/v2010/account/available_phone_number/toll_free.py deleted file mode 100644 index 68f3516e6a..0000000000 --- a/twilio/rest/api/v2010/account/available_phone_number/toll_free.py +++ /dev/null @@ -1,462 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import values -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.page import Page - - -class TollFreeList(ListResource): - """ """ - - def __init__(self, version, account_sid, country_code): - """ - Initialize the TollFreeList - - :param Version version: Version that contains the resource - :param account_sid: The 34 character string that uniquely identifies your account. - :param country_code: The ISO Country code to lookup phone numbers for. - - :returns: twilio.rest.api.v2010.account.available_phone_number.toll_free.TollFreeList - :rtype: twilio.rest.api.v2010.account.available_phone_number.toll_free.TollFreeList - """ - super(TollFreeList, self).__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=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, - exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, limit=None, page_size=None): - """ - 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 unicode area_code: The area_code - :param unicode contains: The contains - :param bool sms_enabled: The sms_enabled - :param bool mms_enabled: The mms_enabled - :param bool voice_enabled: The voice_enabled - :param bool exclude_all_address_required: The exclude_all_address_required - :param bool exclude_local_address_required: The exclude_local_address_required - :param bool exclude_foreign_address_required: The exclude_foreign_address_required - :param bool beta: The beta - :param unicode near_number: The near_number - :param unicode near_lat_long: The near_lat_long - :param unicode distance: The distance - :param unicode in_postal_code: The in_postal_code - :param unicode in_region: The in_region - :param unicode in_rate_center: The in_rate_center - :param unicode in_lata: The in_lata - :param unicode in_locality: The in_locality - :param bool fax_enabled: The fax_enabled - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.available_phone_number.toll_free.TollFreeInstance] - """ - 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'], limits['page_limit']) - - def list(self, area_code=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, limit=None, page_size=None): - """ - 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 unicode area_code: The area_code - :param unicode contains: The contains - :param bool sms_enabled: The sms_enabled - :param bool mms_enabled: The mms_enabled - :param bool voice_enabled: The voice_enabled - :param bool exclude_all_address_required: The exclude_all_address_required - :param bool exclude_local_address_required: The exclude_local_address_required - :param bool exclude_foreign_address_required: The exclude_foreign_address_required - :param bool beta: The beta - :param unicode near_number: The near_number - :param unicode near_lat_long: The near_lat_long - :param unicode distance: The distance - :param unicode in_postal_code: The in_postal_code - :param unicode in_region: The in_region - :param unicode in_rate_center: The in_rate_center - :param unicode in_lata: The in_lata - :param unicode in_locality: The in_locality - :param bool fax_enabled: The fax_enabled - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.available_phone_number.toll_free.TollFreeInstance] - """ - 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, - )) - - def page(self, area_code=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of TollFreeInstance records from the API. - Request is executed immediately - - :param unicode area_code: The area_code - :param unicode contains: The contains - :param bool sms_enabled: The sms_enabled - :param bool mms_enabled: The mms_enabled - :param bool voice_enabled: The voice_enabled - :param bool exclude_all_address_required: The exclude_all_address_required - :param bool exclude_local_address_required: The exclude_local_address_required - :param bool exclude_foreign_address_required: The exclude_foreign_address_required - :param bool beta: The beta - :param unicode near_number: The near_number - :param unicode near_lat_long: The near_lat_long - :param unicode distance: The distance - :param unicode in_postal_code: The in_postal_code - :param unicode in_region: The in_region - :param unicode in_rate_center: The in_rate_center - :param unicode in_lata: The in_lata - :param unicode in_locality: The in_locality - :param bool fax_enabled: The fax_enabled - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of TollFreeInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.toll_free.TollFreePage - """ - params = values.of({ - 'AreaCode': area_code, - 'Contains': contains, - 'SmsEnabled': sms_enabled, - 'MmsEnabled': mms_enabled, - 'VoiceEnabled': voice_enabled, - 'ExcludeAllAddressRequired': exclude_all_address_required, - 'ExcludeLocalAddressRequired': exclude_local_address_required, - 'ExcludeForeignAddressRequired': exclude_foreign_address_required, - 'Beta': 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': fax_enabled, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return TollFreePage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of TollFreeInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of TollFreeInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.toll_free.TollFreePage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return TollFreePage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class TollFreePage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the TollFreePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The 34 character string that uniquely identifies your account. - :param country_code: The ISO Country code to lookup phone numbers for. - - :returns: twilio.rest.api.v2010.account.available_phone_number.toll_free.TollFreePage - :rtype: twilio.rest.api.v2010.account.available_phone_number.toll_free.TollFreePage - """ - super(TollFreePage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of TollFreeInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.available_phone_number.toll_free.TollFreeInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.toll_free.TollFreeInstance - """ - return TollFreeInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - country_code=self._solution['country_code'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class TollFreeInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid, country_code): - """ - Initialize the TollFreeInstance - - :returns: twilio.rest.api.v2010.account.available_phone_number.toll_free.TollFreeInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.toll_free.TollFreeInstance - """ - super(TollFreeInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'friendly_name': payload['friendly_name'], - 'phone_number': payload['phone_number'], - 'lata': payload['lata'], - 'locality': payload['locality'], - 'rate_center': payload['rate_center'], - 'latitude': deserialize.decimal(payload['latitude']), - 'longitude': deserialize.decimal(payload['longitude']), - 'region': payload['region'], - 'postal_code': payload['postal_code'], - 'iso_country': payload['iso_country'], - 'address_requirements': payload['address_requirements'], - 'beta': payload['beta'], - 'capabilities': payload['capabilities'], - } - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'country_code': country_code, } - - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def phone_number(self): - """ - :returns: The phone_number - :rtype: unicode - """ - return self._properties['phone_number'] - - @property - def lata(self): - """ - :returns: The lata - :rtype: unicode - """ - return self._properties['lata'] - - @property - def locality(self): - """ - :returns: The locality - :rtype: unicode - """ - return self._properties['locality'] - - @property - def rate_center(self): - """ - :returns: The rate_center - :rtype: unicode - """ - return self._properties['rate_center'] - - @property - def latitude(self): - """ - :returns: The latitude - :rtype: unicode - """ - return self._properties['latitude'] - - @property - def longitude(self): - """ - :returns: The longitude - :rtype: unicode - """ - return self._properties['longitude'] - - @property - def region(self): - """ - :returns: The region - :rtype: unicode - """ - return self._properties['region'] - - @property - def postal_code(self): - """ - :returns: The postal_code - :rtype: unicode - """ - return self._properties['postal_code'] - - @property - def iso_country(self): - """ - :returns: The iso_country - :rtype: unicode - """ - return self._properties['iso_country'] - - @property - def address_requirements(self): - """ - :returns: The address_requirements - :rtype: unicode - """ - return self._properties['address_requirements'] - - @property - def beta(self): - """ - :returns: The beta - :rtype: bool - """ - return self._properties['beta'] - - @property - def capabilities(self): - """ - :returns: The capabilities - :rtype: unicode - """ - return self._properties['capabilities'] - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/api/v2010/account/available_phone_number/voip.py b/twilio/rest/api/v2010/account/available_phone_number/voip.py deleted file mode 100644 index 9521f6e269..0000000000 --- a/twilio/rest/api/v2010/account/available_phone_number/voip.py +++ /dev/null @@ -1,462 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import values -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.page import Page - - -class VoipList(ListResource): - """ """ - - def __init__(self, version, account_sid, country_code): - """ - Initialize the VoipList - - :param Version version: Version that contains the resource - :param account_sid: The 34 character string that uniquely identifies your account. - :param country_code: The ISO Country code to lookup phone numbers for. - - :returns: twilio.rest.api.v2010.account.available_phone_number.voip.VoipList - :rtype: twilio.rest.api.v2010.account.available_phone_number.voip.VoipList - """ - super(VoipList, self).__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=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, - exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, limit=None, page_size=None): - """ - 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 unicode area_code: The area_code - :param unicode contains: The contains - :param bool sms_enabled: The sms_enabled - :param bool mms_enabled: The mms_enabled - :param bool voice_enabled: The voice_enabled - :param bool exclude_all_address_required: The exclude_all_address_required - :param bool exclude_local_address_required: The exclude_local_address_required - :param bool exclude_foreign_address_required: The exclude_foreign_address_required - :param bool beta: The beta - :param unicode near_number: The near_number - :param unicode near_lat_long: The near_lat_long - :param unicode distance: The distance - :param unicode in_postal_code: The in_postal_code - :param unicode in_region: The in_region - :param unicode in_rate_center: The in_rate_center - :param unicode in_lata: The in_lata - :param unicode in_locality: The in_locality - :param bool fax_enabled: The fax_enabled - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.available_phone_number.voip.VoipInstance] - """ - 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'], limits['page_limit']) - - def list(self, area_code=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, limit=None, page_size=None): - """ - 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 unicode area_code: The area_code - :param unicode contains: The contains - :param bool sms_enabled: The sms_enabled - :param bool mms_enabled: The mms_enabled - :param bool voice_enabled: The voice_enabled - :param bool exclude_all_address_required: The exclude_all_address_required - :param bool exclude_local_address_required: The exclude_local_address_required - :param bool exclude_foreign_address_required: The exclude_foreign_address_required - :param bool beta: The beta - :param unicode near_number: The near_number - :param unicode near_lat_long: The near_lat_long - :param unicode distance: The distance - :param unicode in_postal_code: The in_postal_code - :param unicode in_region: The in_region - :param unicode in_rate_center: The in_rate_center - :param unicode in_lata: The in_lata - :param unicode in_locality: The in_locality - :param bool fax_enabled: The fax_enabled - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.available_phone_number.voip.VoipInstance] - """ - 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, - )) - - def page(self, area_code=values.unset, contains=values.unset, - sms_enabled=values.unset, mms_enabled=values.unset, - voice_enabled=values.unset, exclude_all_address_required=values.unset, - exclude_local_address_required=values.unset, - exclude_foreign_address_required=values.unset, beta=values.unset, - near_number=values.unset, near_lat_long=values.unset, - distance=values.unset, in_postal_code=values.unset, - in_region=values.unset, in_rate_center=values.unset, - in_lata=values.unset, in_locality=values.unset, - fax_enabled=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of VoipInstance records from the API. - Request is executed immediately - - :param unicode area_code: The area_code - :param unicode contains: The contains - :param bool sms_enabled: The sms_enabled - :param bool mms_enabled: The mms_enabled - :param bool voice_enabled: The voice_enabled - :param bool exclude_all_address_required: The exclude_all_address_required - :param bool exclude_local_address_required: The exclude_local_address_required - :param bool exclude_foreign_address_required: The exclude_foreign_address_required - :param bool beta: The beta - :param unicode near_number: The near_number - :param unicode near_lat_long: The near_lat_long - :param unicode distance: The distance - :param unicode in_postal_code: The in_postal_code - :param unicode in_region: The in_region - :param unicode in_rate_center: The in_rate_center - :param unicode in_lata: The in_lata - :param unicode in_locality: The in_locality - :param bool fax_enabled: The fax_enabled - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of VoipInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.voip.VoipPage - """ - params = values.of({ - 'AreaCode': area_code, - 'Contains': contains, - 'SmsEnabled': sms_enabled, - 'MmsEnabled': mms_enabled, - 'VoiceEnabled': voice_enabled, - 'ExcludeAllAddressRequired': exclude_all_address_required, - 'ExcludeLocalAddressRequired': exclude_local_address_required, - 'ExcludeForeignAddressRequired': exclude_foreign_address_required, - 'Beta': 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': fax_enabled, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return VoipPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of VoipInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of VoipInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.voip.VoipPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return VoipPage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class VoipPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the VoipPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The 34 character string that uniquely identifies your account. - :param country_code: The ISO Country code to lookup phone numbers for. - - :returns: twilio.rest.api.v2010.account.available_phone_number.voip.VoipPage - :rtype: twilio.rest.api.v2010.account.available_phone_number.voip.VoipPage - """ - super(VoipPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of VoipInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.available_phone_number.voip.VoipInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.voip.VoipInstance - """ - return VoipInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - country_code=self._solution['country_code'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class VoipInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid, country_code): - """ - Initialize the VoipInstance - - :returns: twilio.rest.api.v2010.account.available_phone_number.voip.VoipInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.voip.VoipInstance - """ - super(VoipInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'friendly_name': payload['friendly_name'], - 'phone_number': payload['phone_number'], - 'lata': payload['lata'], - 'locality': payload['locality'], - 'rate_center': payload['rate_center'], - 'latitude': deserialize.decimal(payload['latitude']), - 'longitude': deserialize.decimal(payload['longitude']), - 'region': payload['region'], - 'postal_code': payload['postal_code'], - 'iso_country': payload['iso_country'], - 'address_requirements': payload['address_requirements'], - 'beta': payload['beta'], - 'capabilities': payload['capabilities'], - } - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'country_code': country_code, } - - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def phone_number(self): - """ - :returns: The phone_number - :rtype: unicode - """ - return self._properties['phone_number'] - - @property - def lata(self): - """ - :returns: The lata - :rtype: unicode - """ - return self._properties['lata'] - - @property - def locality(self): - """ - :returns: The locality - :rtype: unicode - """ - return self._properties['locality'] - - @property - def rate_center(self): - """ - :returns: The rate_center - :rtype: unicode - """ - return self._properties['rate_center'] - - @property - def latitude(self): - """ - :returns: The latitude - :rtype: unicode - """ - return self._properties['latitude'] - - @property - def longitude(self): - """ - :returns: The longitude - :rtype: unicode - """ - return self._properties['longitude'] - - @property - def region(self): - """ - :returns: The region - :rtype: unicode - """ - return self._properties['region'] - - @property - def postal_code(self): - """ - :returns: The postal_code - :rtype: unicode - """ - return self._properties['postal_code'] - - @property - def iso_country(self): - """ - :returns: The iso_country - :rtype: unicode - """ - return self._properties['iso_country'] - - @property - def address_requirements(self): - """ - :returns: The address_requirements - :rtype: unicode - """ - return self._properties['address_requirements'] - - @property - def beta(self): - """ - :returns: The beta - :rtype: bool - """ - return self._properties['beta'] - - @property - def capabilities(self): - """ - :returns: The capabilities - :rtype: unicode - """ - return self._properties['capabilities'] - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' 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 "".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 "".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 "" + + +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 "" 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 "".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 "" + + +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 "" 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 "".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 "" + + +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 "" 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 "".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 "" + + +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 "" 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 "".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 "" + + +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 "" 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 "".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 "" + + +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 "" 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 "".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 "" + + +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 "" 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 "".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 "" + + +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 "" 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 "".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 "" diff --git a/twilio/rest/api/v2010/account/call/__init__.py b/twilio/rest/api/v2010/account/call/__init__.py index 2488f36ff1..f7756c40ec 100644 --- a/twilio/rest/api/v2010/account/call/__init__.py +++ b/twilio/rest/api/v2010/account/call/__init__.py @@ -1,896 +1,1400 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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.feedback import FeedbackList -from twilio.rest.api.v2010.account.call.feedback_summary import FeedbackSummaryList +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 CallList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the CallList - - :param Version version: Version that contains the resource - :param account_sid: The unique id of the Account responsible for creating this Call +class CallInstance(InstanceResource): - :returns: twilio.rest.api.v2010.account.call.CallList - :rtype: twilio.rest.api.v2010.account.call.CallList - """ - super(CallList, self).__init__(version) + class Status(object): + QUEUED = "queued" + RINGING = "ringing" + IN_PROGRESS = "in-progress" + COMPLETED = "completed" + BUSY = "busy" + FAILED = "failed" + NO_ANSWER = "no-answer" + CANCELED = "canceled" - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Calls.json'.format(**self._solution) - - # Components - self._feedback_summaries = None - - def create(self, to, from_, method=values.unset, fallback_url=values.unset, - fallback_method=values.unset, status_callback=values.unset, - status_callback_event=values.unset, - status_callback_method=values.unset, send_digits=values.unset, - if_machine=values.unset, timeout=values.unset, record=values.unset, - recording_channels=values.unset, - recording_status_callback=values.unset, - recording_status_callback_method=values.unset, - sip_auth_username=values.unset, sip_auth_password=values.unset, - machine_detection=values.unset, - machine_detection_timeout=values.unset, - recording_status_callback_event=values.unset, trim=values.unset, - caller_id=values.unset, url=values.unset, - application_sid=values.unset): - """ - Create a new CallInstance - - :param unicode to: Phone number, SIP address or client identifier to call - :param unicode from_: Twilio number from which to originate the call - :param unicode method: HTTP method to use to fetch TwiML - :param unicode fallback_url: Fallback URL in case of error - :param unicode fallback_method: HTTP Method to use with FallbackUrl - :param unicode status_callback: Status Callback URL - :param unicode status_callback_event: The status_callback_event - :param unicode status_callback_method: HTTP Method to use with StatusCallback - :param unicode send_digits: Digits to send - :param unicode if_machine: Action to take if a machine has answered the call - :param unicode timeout: Number of seconds to wait for an answer - :param bool record: Whether or not to record the Call - :param unicode recording_channels: The recording_channels - :param unicode recording_status_callback: The recording_status_callback - :param unicode recording_status_callback_method: The recording_status_callback_method - :param unicode sip_auth_username: The sip_auth_username - :param unicode sip_auth_password: The sip_auth_password - :param unicode machine_detection: Enable machine detection or end of greeting detection - :param unicode machine_detection_timeout: Number of miliseconds to wait for machine detection - :param unicode recording_status_callback_event: The recording_status_callback_event - :param unicode trim: Set this parameter to control trimming of silence on the recording. - :param unicode caller_id: The phone number, SIP address or Client identifier that made this Call. Phone numbers are in E.164 format (e.g. +16175551212). SIP addresses are formatted as `name@company.com`. - :param unicode url: Url from which to fetch TwiML - :param unicode application_sid: ApplicationSid that configures from where to fetch TwiML - - :returns: Newly created CallInstance - :rtype: twilio.rest.api.v2010.account.call.CallInstance - """ - data = values.of({ - 'To': to, - 'From': from_, - 'Url': url, - 'ApplicationSid': application_sid, - '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, - 'IfMachine': if_machine, - 'Timeout': timeout, - 'Record': 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, - }) + class UpdateStatus(object): + CANCELED = "canceled" + COMPLETED = "completed" - payload = self._version.create( - 'POST', - self._uri, - data=data, + """ + :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 `` 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" ) - return CallInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[CallContext] = None - def stream(self, to=values.unset, from_=values.unset, - parent_call_sid=values.unset, status=values.unset, - start_time_before=values.unset, start_time=values.unset, - start_time_after=values.unset, end_time_before=values.unset, - end_time=values.unset, end_time_after=values.unset, limit=None, - page_size=None): + @property + def _proxy(self) -> "CallContext": """ - 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. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param unicode to: Phone number or Client identifier to filter `to` on - :param unicode from_: Phone number or Client identifier to filter `from` on - :param unicode parent_call_sid: Parent Call Sid to filter on - :param CallInstance.Status status: Status to filter on - :param datetime start_time_before: StartTime to filter on - :param datetime start_time: StartTime to filter on - :param datetime start_time_after: StartTime to filter on - :param datetime end_time_before: EndTime to filter on - :param datetime end_time: EndTime to filter on - :param datetime end_time_after: EndTime to filter on - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.call.CallInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the CallInstance - page = self.page( - to=to, - from_=from_, - parent_call_sid=parent_call_sid, - status=status, - start_time_before=start_time_before, - start_time=start_time, - start_time_after=start_time_after, - end_time_before=end_time_before, - end_time=end_time, - end_time_after=end_time_after, - page_size=limits['page_size'], - ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, to=values.unset, from_=values.unset, - parent_call_sid=values.unset, status=values.unset, - start_time_before=values.unset, start_time=values.unset, - start_time_after=values.unset, end_time_before=values.unset, - end_time=values.unset, end_time_after=values.unset, limit=None, - page_size=None): + async def delete_async(self) -> bool: """ - Lists CallInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the CallInstance - :param unicode to: Phone number or Client identifier to filter `to` on - :param unicode from_: Phone number or Client identifier to filter `from` on - :param unicode parent_call_sid: Parent Call Sid to filter on - :param CallInstance.Status status: Status to filter on - :param datetime start_time_before: StartTime to filter on - :param datetime start_time: StartTime to filter on - :param datetime start_time_after: StartTime to filter on - :param datetime end_time_before: EndTime to filter on - :param datetime end_time: EndTime to filter on - :param datetime end_time_after: EndTime to filter on - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.call.CallInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream( - to=to, - from_=from_, - parent_call_sid=parent_call_sid, - status=status, - start_time_before=start_time_before, - start_time=start_time, - start_time_after=start_time_after, - end_time_before=end_time_before, - end_time=end_time, - end_time_after=end_time_after, - limit=limit, - page_size=page_size, - )) - - def page(self, to=values.unset, from_=values.unset, - parent_call_sid=values.unset, status=values.unset, - start_time_before=values.unset, start_time=values.unset, - start_time_after=values.unset, end_time_before=values.unset, - end_time=values.unset, end_time_after=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + return await self._proxy.delete_async() + + def fetch(self) -> "CallInstance": """ - Retrieve a single page of CallInstance records from the API. - Request is executed immediately + Fetch the CallInstance - :param unicode to: Phone number or Client identifier to filter `to` on - :param unicode from_: Phone number or Client identifier to filter `from` on - :param unicode parent_call_sid: Parent Call Sid to filter on - :param CallInstance.Status status: Status to filter on - :param datetime start_time_before: StartTime to filter on - :param datetime start_time: StartTime to filter on - :param datetime start_time_after: StartTime to filter on - :param datetime end_time_before: EndTime to filter on - :param datetime end_time: EndTime to filter on - :param datetime end_time_after: EndTime to filter on - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of CallInstance - :rtype: twilio.rest.api.v2010.account.call.CallPage - """ - params = values.of({ - 'To': to, - 'From': from_, - 'ParentCallSid': parent_call_sid, - 'Status': status, - 'StartTime<': serialize.iso8601_datetime(start_time_before), - 'StartTime': serialize.iso8601_datetime(start_time), - 'StartTime>': serialize.iso8601_datetime(start_time_after), - 'EndTime<': serialize.iso8601_datetime(end_time_before), - 'EndTime': serialize.iso8601_datetime(end_time), - 'EndTime>': serialize.iso8601_datetime(end_time_after), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + :returns: The fetched CallInstance + """ + return self._proxy.fetch() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + async def fetch_async(self) -> "CallInstance": + """ + Asynchronous coroutine to fetch the CallInstance - return CallPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched CallInstance """ - Retrieve a specific page of CallInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_async() - :param str target_url: API-generated URL for the requested results page + 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 - :returns: Page of CallInstance - :rtype: twilio.rest.api.v2010.account.call.CallPage + :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 """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, ) - return CallPage(self._version, response, self._solution) + 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 feedback_summaries(self): + def events(self) -> EventList: + """ + Access the events """ - Access the feedback_summaries + return self._proxy.events - :returns: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryList - :rtype: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryList + @property + def notifications(self) -> NotificationList: """ - if self._feedback_summaries is None: - self._feedback_summaries = FeedbackSummaryList( - self._version, - account_sid=self._solution['account_sid'], - ) - return self._feedback_summaries + Access the notifications + """ + return self._proxy.notifications - def get(self, sid): + @property + def payments(self) -> PaymentList: """ - Constructs a CallContext + Access the payments + """ + return self._proxy.payments - :param sid: Call Sid that uniquely identifies the Call to fetch + @property + def recordings(self) -> RecordingList: + """ + Access the recordings + """ + return self._proxy.recordings - :returns: twilio.rest.api.v2010.account.call.CallContext - :rtype: twilio.rest.api.v2010.account.call.CallContext + @property + def siprec(self) -> SiprecList: + """ + Access the siprec """ - return CallContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.siprec - def __call__(self, sid): + @property + def streams(self) -> StreamList: """ - Constructs a CallContext + Access the streams + """ + return self._proxy.streams + + @property + def transcriptions(self) -> TranscriptionList: + """ + Access the transcriptions + """ + return self._proxy.transcriptions - :param sid: Call Sid that uniquely identifies the Call to fetch + @property + def user_defined_messages(self) -> UserDefinedMessageList: + """ + Access the user_defined_messages + """ + return self._proxy.user_defined_messages - :returns: twilio.rest.api.v2010.account.call.CallContext - :rtype: twilio.rest.api.v2010.account.call.CallContext + @property + def user_defined_message_subscriptions(self) -> UserDefinedMessageSubscriptionList: + """ + Access the user_defined_message_subscriptions """ - return CallContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.user_defined_message_subscriptions - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class CallPage(Page): - """ """ +class CallContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str, sid: str): """ - Initialize the CallPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The unique id of the Account responsible for creating this Call + Initialize the CallContext - :returns: twilio.rest.api.v2010.account.call.CallPage - :rtype: twilio.rest.api.v2010.account.call.CallPage + :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(CallPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution - - def get_instance(self, payload): + 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: """ - Build an instance of CallInstance + Deletes the CallInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.api.v2010.account.call.CallInstance - :rtype: twilio.rest.api.v2010.account.call.CallInstance + :returns: True if delete succeeds, False otherwise """ - return CallInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the CallInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class CallContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, account_sid, sid): + def fetch(self) -> CallInstance: """ - Initialize the CallContext + Fetch the CallInstance - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param sid: Call Sid that uniquely identifies the Call to fetch - :returns: twilio.rest.api.v2010.account.call.CallContext - :rtype: twilio.rest.api.v2010.account.call.CallContext + :returns: The fetched CallInstance """ - super(CallContext, self).__init__(version) - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/Calls/{sid}.json'.format(**self._solution) + headers = values.of({}) - # Dependents - self._recordings = None - self._notifications = None - self._feedback = None + headers["Accept"] = "application/json" - def delete(self): - """ - Deletes the CallInstance + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + return CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - def fetch(self): + async def fetch_async(self) -> CallInstance: """ - Fetch a CallInstance + Asynchronous coroutine to fetch the CallInstance - :returns: Fetched CallInstance - :rtype: twilio.rest.api.v2010.account.call.CallInstance + + :returns: The fetched CallInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def update(self, url=values.unset, method=values.unset, status=values.unset, - fallback_url=values.unset, fallback_method=values.unset, - status_callback=values.unset, status_callback_method=values.unset): + 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 unicode url: URL that returns TwiML - :param unicode method: HTTP method to use to fetch TwiML - :param CallInstance.UpdateStatus status: Status to update the Call with - :param unicode fallback_url: Fallback URL in case of error - :param unicode fallback_method: HTTP Method to use with FallbackUrl - :param unicode status_callback: Status Callback URL - :param unicode status_callback_method: HTTP Method to use with StatusCallback - - :returns: Updated CallInstance - :rtype: twilio.rest.api.v2010.account.call.CallInstance - """ - data = values.of({ - 'Url': url, - 'Method': method, - 'Status': status, - 'FallbackUrl': fallback_url, - 'FallbackMethod': fallback_method, - 'StatusCallback': status_callback, - 'StatusCallbackMethod': status_callback_method, - }) + :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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) return CallInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + 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 recordings(self): + def events(self) -> EventList: """ - Access the recordings - - :returns: twilio.rest.api.v2010.account.call.recording.RecordingList - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingList + Access the events """ - if self._recordings is None: - self._recordings = RecordingList( + if self._events is None: + self._events = EventList( self._version, - account_sid=self._solution['account_sid'], - call_sid=self._solution['sid'], + self._solution["account_sid"], + self._solution["sid"], ) - return self._recordings + return self._events @property - def notifications(self): + def notifications(self) -> NotificationList: """ Access the notifications - - :returns: twilio.rest.api.v2010.account.call.notification.NotificationList - :rtype: twilio.rest.api.v2010.account.call.notification.NotificationList """ if self._notifications is None: self._notifications = NotificationList( self._version, - account_sid=self._solution['account_sid'], - call_sid=self._solution['sid'], + self._solution["account_sid"], + self._solution["sid"], ) return self._notifications @property - def feedback(self): + def payments(self) -> PaymentList: """ - Access the feedback - - :returns: twilio.rest.api.v2010.account.call.feedback.FeedbackList - :rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackList + Access the payments """ - if self._feedback is None: - self._feedback = FeedbackList( + if self._payments is None: + self._payments = PaymentList( self._version, - account_sid=self._solution['account_sid'], - call_sid=self._solution['sid'], + self._solution["account_sid"], + self._solution["sid"], ) - return self._feedback - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class CallInstance(InstanceResource): - """ """ - - class Event(object): - INITIATED = "initiated" - RINGING = "ringing" - ANSWERED = "answered" - COMPLETED = "completed" - - 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" - - def __init__(self, version, payload, account_sid, sid=None): - """ - Initialize the CallInstance - - :returns: twilio.rest.api.v2010.account.call.CallInstance - :rtype: twilio.rest.api.v2010.account.call.CallInstance - """ - super(CallInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'annotation': payload['annotation'], - 'answered_by': payload['answered_by'], - 'api_version': payload['api_version'], - 'caller_name': payload['caller_name'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'direction': payload['direction'], - 'duration': payload['duration'], - 'end_time': deserialize.rfc2822_datetime(payload['end_time']), - 'forwarded_from': payload['forwarded_from'], - 'from_': payload['from'], - 'from_formatted': payload['from_formatted'], - 'group_sid': payload['group_sid'], - 'parent_call_sid': payload['parent_call_sid'], - 'phone_number_sid': payload['phone_number_sid'], - 'price': deserialize.decimal(payload['price']), - 'price_unit': payload['price_unit'], - 'sid': payload['sid'], - 'start_time': deserialize.rfc2822_datetime(payload['start_time']), - 'status': payload['status'], - 'subresource_uris': payload['subresource_uris'], - 'to': payload['to'], - 'to_formatted': payload['to_formatted'], - 'uri': payload['uri'], - } - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } + return self._payments @property - def _proxy(self): + def recordings(self) -> RecordingList: """ - 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 - :rtype: twilio.rest.api.v2010.account.call.CallContext + Access the recordings """ - if self._context is None: - self._context = CallContext( + if self._recordings is None: + self._recordings = RecordingList( self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + self._solution["account_sid"], + self._solution["sid"], ) - return self._context + return self._recordings @property - def account_sid(self): + def siprec(self) -> SiprecList: """ - :returns: The unique id of the Account responsible for creating this Call - :rtype: unicode + Access the siprec """ - return self._properties['account_sid'] + if self._siprec is None: + self._siprec = SiprecList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._siprec @property - def annotation(self): + def streams(self) -> StreamList: """ - :returns: The annotation provided for the Call - :rtype: unicode + Access the streams """ - return self._properties['annotation'] + if self._streams is None: + self._streams = StreamList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._streams @property - def answered_by(self): + def transcriptions(self) -> TranscriptionList: """ - :returns: If this call was initiated with answering machine detection, either `human` or `machine`. Empty otherwise. - :rtype: unicode + Access the transcriptions """ - return self._properties['answered_by'] + if self._transcriptions is None: + self._transcriptions = TranscriptionList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._transcriptions @property - def api_version(self): + def user_defined_messages(self) -> UserDefinedMessageList: """ - :returns: The API Version the Call was created through - :rtype: unicode + Access the user_defined_messages """ - return self._properties['api_version'] + 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 caller_name(self): + def user_defined_message_subscriptions(self) -> UserDefinedMessageSubscriptionList: """ - :returns: If this call was an incoming call to a phone number with Caller ID Lookup enabled, the caller's name. Empty otherwise. - :rtype: unicode + Access the user_defined_message_subscriptions """ - return self._properties['caller_name'] + 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 - @property - def date_created(self): - """ - :returns: The date that this resource was created - :rtype: datetime + def __repr__(self) -> str: """ - return self._properties['date_created'] + Provide a friendly representation - @property - def date_updated(self): - """ - :returns: The date that this resource was last updated - :rtype: datetime + :returns: Machine friendly representation """ - return self._properties['date_updated'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def direction(self): - """ - :returns: 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 `Dial` verb. - :rtype: unicode - """ - return self._properties['direction'] - @property - def duration(self): - """ - :returns: The duration - :rtype: unicode - """ - return self._properties['duration'] +class CallPage(Page): - @property - def end_time(self): - """ - :returns: The end time of the Call. Null if the call did not complete successfully. - :rtype: datetime + def get_instance(self, payload: Dict[str, Any]) -> CallInstance: """ - return self._properties['end_time'] + Build an instance of CallInstance - @property - def forwarded_from(self): - """ - :returns: If this Call was an incoming call forwarded from another number, the forwarding phone number (depends on carrier supporting forwarding). Empty otherwise. - :rtype: unicode + :param payload: Payload response from the API """ - return self._properties['forwarded_from'] + return CallInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def from_(self): + def __repr__(self) -> str: """ - :returns: The phone number, SIP address or Client identifier that made this Call. Phone numbers are in E.164 format (e.g. +16175551212). SIP addresses are formatted as `name@company.com`. Client identifiers are formatted `client:name`. - :rtype: unicode - """ - return self._properties['from_'] + Provide a friendly representation - @property - def from_formatted(self): - """ - :returns: The phone number, SIP address or Client identifier that made this Call. Formatted for display. - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['from_formatted'] + return "" - @property - def group_sid(self): - """ - :returns: A 34 character Group Sid associated with this Call. Empty if no Group is associated with the Call. - :rtype: unicode - """ - return self._properties['group_sid'] - @property - def parent_call_sid(self): - """ - :returns: A 34 character string that uniquely identifies the Call that created this leg. - :rtype: unicode - """ - return self._properties['parent_call_sid'] +class CallList(ListResource): - @property - def phone_number_sid(self): + def __init__(self, version: Version, account_sid: str): """ - :returns: 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. - :rtype: unicode - """ - return self._properties['phone_number_sid'] + Initialize the CallList - @property - def price(self): - """ - :returns: The charge for this call, in the currency associated with the account. Populated after the call is completed. May not be immediately available. - :rtype: unicode - """ - return self._properties['price'] + :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. - @property - def price_unit(self): - """ - :returns: The currency in which `Price` is measured. - :rtype: unicode """ - return self._properties['price_unit'] + super().__init__(version) - @property - def sid(self): - """ - :returns: A 34 character string that uniquely identifies this resource. - :rtype: unicode - """ - return self._properties['sid'] + # 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"}) - @property - def start_time(self): - """ - :returns: The start time of the Call. Null if the call has not yet been dialed. - :rtype: datetime - """ - return self._properties['start_time'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def status(self): - """ - :returns: The status - :rtype: CallInstance.Status - """ - return self._properties['status'] + headers["Accept"] = "application/json" - @property - def subresource_uris(self): - """ - :returns: Call Instance Subresources - :rtype: unicode - """ - return self._properties['subresource_uris'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def to(self): - """ - :returns: The phone number, SIP address or Client identifier that received this Call. Phone numbers are in E.164 format (e.g. +16175551212). SIP addresses are formatted as `name@company.com`. Client identifiers are formatted `client:name`. - :rtype: unicode - """ - return self._properties['to'] + return CallInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def to_formatted(self): - """ - :returns: The phone number, SIP address or Client identifier that received this Call. Formatted for display. - :rtype: unicode + 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]: """ - return self._properties['to_formatted'] + 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. - @property - def uri(self): + :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 """ - :returns: The URI for this resource, relative to `https://api.twilio.com` - :rtype: unicode + 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 """ - return self._properties['uri'] + 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"], + ) - def delete(self): + 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]: """ - Deletes the 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. - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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: """ - return self._proxy.delete() + Retrieve a single page of CallInstance records from the API. + Request is executed immediately - def fetch(self): + :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 """ - Fetch a 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 - :returns: Fetched CallInstance - :rtype: twilio.rest.api.v2010.account.call.CallInstance + :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 """ - return self._proxy.fetch() + 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, + } + ) - def update(self, url=values.unset, method=values.unset, status=values.unset, - fallback_url=values.unset, fallback_method=values.unset, - status_callback=values.unset, status_callback_method=values.unset): + headers = values.of({"Content-Type": "application/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: """ - Update the CallInstance + Retrieve a specific page of CallInstance records from the API. + Request is executed immediately - :param unicode url: URL that returns TwiML - :param unicode method: HTTP method to use to fetch TwiML - :param CallInstance.UpdateStatus status: Status to update the Call with - :param unicode fallback_url: Fallback URL in case of error - :param unicode fallback_method: HTTP Method to use with FallbackUrl - :param unicode status_callback: Status Callback URL - :param unicode status_callback_method: HTTP Method to use with StatusCallback + :param target_url: API-generated URL for the requested results page - :returns: Updated CallInstance - :rtype: twilio.rest.api.v2010.account.call.CallInstance + :returns: Page of 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, - ) + response = self._version.domain.twilio.request("GET", target_url) + return CallPage(self._version, response, self._solution) - @property - def recordings(self): + async def get_page_async(self, target_url: str) -> CallPage: """ - Access the recordings + Asynchronously retrieve a specific page of CallInstance records from the API. + Request is executed immediately - :returns: twilio.rest.api.v2010.account.call.recording.RecordingList - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingList + :param target_url: API-generated URL for the requested results page + + :returns: Page of CallInstance """ - return self._proxy.recordings + response = await self._version.domain.twilio.request_async("GET", target_url) + return CallPage(self._version, response, self._solution) - @property - def notifications(self): + def get(self, sid: str) -> CallContext: """ - Access the notifications + Constructs a CallContext - :returns: twilio.rest.api.v2010.account.call.notification.NotificationList - :rtype: twilio.rest.api.v2010.account.call.notification.NotificationList + :param sid: The Twilio-provided string that uniquely identifies the Call resource to update """ - return self._proxy.notifications + return CallContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - @property - def feedback(self): + def __call__(self, sid: str) -> CallContext: """ - Access the feedback + Constructs a CallContext - :returns: twilio.rest.api.v2010.account.call.feedback.FeedbackList - :rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackList + :param sid: The Twilio-provided string that uniquely identifies the Call resource to update """ - return self._proxy.feedback + return CallContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 "".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 "" + + +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 "" diff --git a/twilio/rest/api/v2010/account/call/feedback.py b/twilio/rest/api/v2010/account/call/feedback.py deleted file mode 100644 index edd35309a3..0000000000 --- a/twilio/rest/api/v2010/account/call/feedback.py +++ /dev/null @@ -1,364 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import serialize -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.page import Page - - -class FeedbackList(ListResource): - """ """ - - def __init__(self, version, account_sid, call_sid): - """ - Initialize the FeedbackList - - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param call_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.call.feedback.FeedbackList - :rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackList - """ - super(FeedbackList, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, 'call_sid': call_sid, } - - def get(self): - """ - Constructs a FeedbackContext - - :returns: twilio.rest.api.v2010.account.call.feedback.FeedbackContext - :rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackContext - """ - return FeedbackContext( - self._version, - account_sid=self._solution['account_sid'], - call_sid=self._solution['call_sid'], - ) - - def __call__(self): - """ - Constructs a FeedbackContext - - :returns: twilio.rest.api.v2010.account.call.feedback.FeedbackContext - :rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackContext - """ - return FeedbackContext( - self._version, - account_sid=self._solution['account_sid'], - call_sid=self._solution['call_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class FeedbackPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the FeedbackPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The account_sid - :param call_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.call.feedback.FeedbackPage - :rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackPage - """ - super(FeedbackPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of FeedbackInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.call.feedback.FeedbackInstance - :rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackInstance - """ - return FeedbackInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - call_sid=self._solution['call_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class FeedbackContext(InstanceContext): - """ """ - - def __init__(self, version, account_sid, call_sid): - """ - Initialize the FeedbackContext - - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param call_sid: The call sid that uniquely identifies the call - - :returns: twilio.rest.api.v2010.account.call.feedback.FeedbackContext - :rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackContext - """ - super(FeedbackContext, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, 'call_sid': call_sid, } - self._uri = '/Accounts/{account_sid}/Calls/{call_sid}/Feedback.json'.format(**self._solution) - - def create(self, quality_score, issue=values.unset): - """ - Create a new FeedbackInstance - - :param unicode quality_score: The quality_score - :param FeedbackInstance.Issues issue: The issue - - :returns: Newly created FeedbackInstance - :rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackInstance - """ - data = values.of({'QualityScore': quality_score, 'Issue': serialize.map(issue, lambda e: e), }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return FeedbackInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - call_sid=self._solution['call_sid'], - ) - - def fetch(self): - """ - Fetch a FeedbackInstance - - :returns: Fetched FeedbackInstance - :rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return FeedbackInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - call_sid=self._solution['call_sid'], - ) - - def update(self, quality_score, issue=values.unset): - """ - Update the FeedbackInstance - - :param unicode quality_score: An integer from 1 to 5 - :param FeedbackInstance.Issues issue: Issues experienced during the call - - :returns: Updated FeedbackInstance - :rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackInstance - """ - data = values.of({'QualityScore': quality_score, 'Issue': serialize.map(issue, lambda e: e), }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return FeedbackInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - call_sid=self._solution['call_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class FeedbackInstance(InstanceResource): - """ """ - - class Issues(object): - AUDIO_LATENCY = "audio-latency" - DIGITS_NOT_CAPTURED = "digits-not-captured" - DROPPED_CALL = "dropped-call" - IMPERFECT_AUDIO = "imperfect-audio" - INCORRECT_CALLER_ID = "incorrect-caller-id" - ONE_WAY_AUDIO = "one-way-audio" - POST_DIAL_DELAY = "post-dial-delay" - UNSOLICITED_CALL = "unsolicited-call" - - def __init__(self, version, payload, account_sid, call_sid): - """ - Initialize the FeedbackInstance - - :returns: twilio.rest.api.v2010.account.call.feedback.FeedbackInstance - :rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackInstance - """ - super(FeedbackInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'issues': payload['issues'], - 'quality_score': deserialize.integer(payload['quality_score']), - 'sid': payload['sid'], - } - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'call_sid': call_sid, } - - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: FeedbackContext for this FeedbackInstance - :rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackContext - """ - if self._context is None: - self._context = FeedbackContext( - self._version, - account_sid=self._solution['account_sid'], - call_sid=self._solution['call_sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def issues(self): - """ - :returns: The issues - :rtype: FeedbackInstance.Issues - """ - return self._properties['issues'] - - @property - def quality_score(self): - """ - :returns: 1 to 5 quality score - :rtype: unicode - """ - return self._properties['quality_score'] - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] - - def create(self, quality_score, issue=values.unset): - """ - Create a new FeedbackInstance - - :param unicode quality_score: The quality_score - :param FeedbackInstance.Issues issue: The issue - - :returns: Newly created FeedbackInstance - :rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackInstance - """ - return self._proxy.create(quality_score, issue=issue, ) - - def fetch(self): - """ - Fetch a FeedbackInstance - - :returns: Fetched FeedbackInstance - :rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackInstance - """ - return self._proxy.fetch() - - def update(self, quality_score, issue=values.unset): - """ - Update the FeedbackInstance - - :param unicode quality_score: An integer from 1 to 5 - :param FeedbackInstance.Issues issue: Issues experienced during the call - - :returns: Updated FeedbackInstance - :rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackInstance - """ - return self._proxy.update(quality_score, issue=issue, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/api/v2010/account/call/feedback_summary.py b/twilio/rest/api/v2010/account/call/feedback_summary.py deleted file mode 100644 index aa86d85b74..0000000000 --- a/twilio/rest/api/v2010/account/call/feedback_summary.py +++ /dev/null @@ -1,396 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import serialize -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.page import Page - - -class FeedbackSummaryList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the FeedbackSummaryList - - :param Version version: Version that contains the resource - :param account_sid: The unique id of the Account responsible for creating this Call - - :returns: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryList - :rtype: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryList - """ - super(FeedbackSummaryList, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Calls/FeedbackSummary.json'.format(**self._solution) - - def create(self, start_date, end_date, include_subaccounts=values.unset, - status_callback=values.unset, status_callback_method=values.unset): - """ - Create a new FeedbackSummaryInstance - - :param date start_date: The start_date - :param date end_date: The end_date - :param bool include_subaccounts: The include_subaccounts - :param unicode status_callback: The status_callback - :param unicode status_callback_method: The status_callback_method - - :returns: Newly created FeedbackSummaryInstance - :rtype: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryInstance - """ - data = values.of({ - 'StartDate': serialize.iso8601_date(start_date), - 'EndDate': serialize.iso8601_date(end_date), - 'IncludeSubaccounts': include_subaccounts, - 'StatusCallback': status_callback, - 'StatusCallbackMethod': status_callback_method, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return FeedbackSummaryInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - def get(self, sid): - """ - Constructs a FeedbackSummaryContext - - :param sid: The sid - - :returns: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryContext - :rtype: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryContext - """ - return FeedbackSummaryContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a FeedbackSummaryContext - - :param sid: The sid - - :returns: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryContext - :rtype: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryContext - """ - return FeedbackSummaryContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class FeedbackSummaryPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the FeedbackSummaryPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The unique id of the Account responsible for creating this Call - - :returns: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryPage - :rtype: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryPage - """ - super(FeedbackSummaryPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of FeedbackSummaryInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryInstance - :rtype: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryInstance - """ - return FeedbackSummaryInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class FeedbackSummaryContext(InstanceContext): - """ """ - - def __init__(self, version, account_sid, sid): - """ - Initialize the FeedbackSummaryContext - - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param sid: The sid - - :returns: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryContext - :rtype: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryContext - """ - super(FeedbackSummaryContext, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/Calls/FeedbackSummary/{sid}.json'.format(**self._solution) - - def fetch(self): - """ - Fetch a FeedbackSummaryInstance - - :returns: Fetched FeedbackSummaryInstance - :rtype: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return FeedbackSummaryInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the FeedbackSummaryInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class FeedbackSummaryInstance(InstanceResource): - """ """ - - class Status(object): - QUEUED = "queued" - IN_PROGRESS = "in-progress" - COMPLETED = "completed" - FAILED = "failed" - - def __init__(self, version, payload, account_sid, sid=None): - """ - Initialize the FeedbackSummaryInstance - - :returns: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryInstance - :rtype: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryInstance - """ - super(FeedbackSummaryInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'call_count': deserialize.integer(payload['call_count']), - 'call_feedback_count': deserialize.integer(payload['call_feedback_count']), - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'end_date': deserialize.iso8601_datetime(payload['end_date']), - 'include_subaccounts': payload['include_subaccounts'], - 'issues': payload['issues'], - 'quality_score_average': deserialize.decimal(payload['quality_score_average']), - 'quality_score_median': deserialize.decimal(payload['quality_score_median']), - 'quality_score_standard_deviation': deserialize.decimal(payload['quality_score_standard_deviation']), - 'sid': payload['sid'], - 'start_date': deserialize.iso8601_datetime(payload['start_date']), - 'status': payload['status'], - } - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: FeedbackSummaryContext for this FeedbackSummaryInstance - :rtype: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryContext - """ - if self._context is None: - self._context = FeedbackSummaryContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def call_count(self): - """ - :returns: The call_count - :rtype: unicode - """ - return self._properties['call_count'] - - @property - def call_feedback_count(self): - """ - :returns: The call_feedback_count - :rtype: unicode - """ - return self._properties['call_feedback_count'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def end_date(self): - """ - :returns: The end_date - :rtype: datetime - """ - return self._properties['end_date'] - - @property - def include_subaccounts(self): - """ - :returns: The include_subaccounts - :rtype: bool - """ - return self._properties['include_subaccounts'] - - @property - def issues(self): - """ - :returns: The issues - :rtype: unicode - """ - return self._properties['issues'] - - @property - def quality_score_average(self): - """ - :returns: The quality_score_average - :rtype: unicode - """ - return self._properties['quality_score_average'] - - @property - def quality_score_median(self): - """ - :returns: The quality_score_median - :rtype: unicode - """ - return self._properties['quality_score_median'] - - @property - def quality_score_standard_deviation(self): - """ - :returns: The quality_score_standard_deviation - :rtype: unicode - """ - return self._properties['quality_score_standard_deviation'] - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] - - @property - def start_date(self): - """ - :returns: The start_date - :rtype: datetime - """ - return self._properties['start_date'] - - @property - def status(self): - """ - :returns: The status - :rtype: FeedbackSummaryInstance.Status - """ - return self._properties['status'] - - def fetch(self): - """ - Fetch a FeedbackSummaryInstance - - :returns: Fetched FeedbackSummaryInstance - :rtype: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the FeedbackSummaryInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/api/v2010/account/call/notification.py b/twilio/rest/api/v2010/account/call/notification.py index c6e0e5e776..fd9e8c0d00 100644 --- a/twilio/rest/api/v2010/account/call/notification.py +++ b/twilio/rest/api/v2010/account/call/notification.py @@ -1,531 +1,562 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 NotificationList(ListResource): - """ """ - - def __init__(self, version, account_sid, call_sid): - """ - Initialize the NotificationList +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") - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param call_sid: The call_sid + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid or self.sid, + } + self._context: Optional[NotificationContext] = None - :returns: twilio.rest.api.v2010.account.call.notification.NotificationList - :rtype: twilio.rest.api.v2010.account.call.notification.NotificationList + @property + def _proxy(self) -> "NotificationContext": """ - super(NotificationList, self).__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) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def stream(self, log=values.unset, message_date_before=values.unset, - message_date=values.unset, message_date_after=values.unset, - limit=None, page_size=None): + :returns: NotificationContext for this 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 unicode log: The log - :param date message_date_before: The message_date - :param date message_date: The message_date - :param date message_date_after: The message_date - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + 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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.call.notification.NotificationInstance] + def fetch(self) -> "NotificationInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the NotificationInstance - page = self.page( - log=log, - message_date_before=message_date_before, - message_date=message_date, - message_date_after=message_date_after, - page_size=limits['page_size'], - ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched NotificationInstance + """ + return self._proxy.fetch() - def list(self, log=values.unset, message_date_before=values.unset, - message_date=values.unset, message_date_after=values.unset, limit=None, - page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the NotificationInstance - :param unicode log: The log - :param date message_date_before: The message_date - :param date message_date: The message_date - :param date message_date_after: The message_date - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.call.notification.NotificationInstance] + :returns: The fetched NotificationInstance """ - return list(self.stream( - log=log, - message_date_before=message_date_before, - message_date=message_date, - message_date_after=message_date_after, - limit=limit, - page_size=page_size, - )) + return await self._proxy.fetch_async() - def page(self, log=values.unset, message_date_before=values.unset, - message_date=values.unset, message_date_after=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def __repr__(self) -> str: """ - Retrieve a single page of NotificationInstance records from the API. - Request is executed immediately + Provide a friendly representation - :param unicode log: The log - :param date message_date_before: The message_date - :param date message_date: The message_date - :param date message_date_after: The message_date - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: Page of NotificationInstance - :rtype: twilio.rest.api.v2010.account.call.notification.NotificationPage - """ - params = values.of({ - 'Log': log, - 'MessageDate<': serialize.iso8601_date(message_date_before), - 'MessageDate': serialize.iso8601_date(message_date), - 'MessageDate>': serialize.iso8601_date(message_date_after), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - response = self._version.page( - 'GET', - self._uri, - params=params, - ) +class NotificationContext(InstanceContext): - return NotificationPage(self._version, response, self._solution) + def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): + """ + Initialize the NotificationContext - def get_page(self, target_url): + :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. """ - Retrieve a specific page of NotificationInstance records from the API. - Request is executed immediately + super().__init__(version) - :param str target_url: API-generated URL for the requested results page + # 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 + ) + ) - :returns: Page of NotificationInstance - :rtype: twilio.rest.api.v2010.account.call.notification.NotificationPage + def fetch(self) -> NotificationInstance: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Fetch the NotificationInstance - return NotificationPage(self._version, response, self._solution) - def get(self, sid): + :returns: The fetched NotificationInstance """ - Constructs a NotificationContext - :param sid: The sid + headers = values.of({}) - :returns: twilio.rest.api.v2010.account.call.notification.NotificationContext - :rtype: twilio.rest.api.v2010.account.call.notification.NotificationContext - """ - return NotificationContext( + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return NotificationInstance( self._version, - account_sid=self._solution['account_sid'], - call_sid=self._solution['call_sid'], - sid=sid, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], ) - def __call__(self, sid): + async def fetch_async(self) -> NotificationInstance: """ - Constructs a NotificationContext + Asynchronous coroutine to fetch the NotificationInstance - :param sid: The sid - :returns: twilio.rest.api.v2010.account.call.notification.NotificationContext - :rtype: twilio.rest.api.v2010.account.call.notification.NotificationContext + :returns: The fetched NotificationInstance """ - return NotificationContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return NotificationInstance( self._version, - account_sid=self._solution['account_sid'], - call_sid=self._solution['call_sid'], - sid=sid, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) class NotificationPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the NotificationPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The account_sid - :param call_sid: The call_sid - :returns: twilio.rest.api.v2010.account.call.notification.NotificationPage - :rtype: twilio.rest.api.v2010.account.call.notification.NotificationPage - """ - super(NotificationPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): + def get_instance(self, payload: Dict[str, Any]) -> NotificationInstance: """ Build an instance of NotificationInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.call.notification.NotificationInstance - :rtype: twilio.rest.api.v2010.account.call.notification.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'], + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class NotificationContext(InstanceContext): - """ """ +class NotificationList(ListResource): - def __init__(self, version, account_sid, call_sid, sid): + def __init__(self, version: Version, account_sid: str, call_sid: str): """ - Initialize the NotificationContext + Initialize the NotificationList - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param call_sid: The call_sid - :param sid: The sid + :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. - :returns: twilio.rest.api.v2010.account.call.notification.NotificationContext - :rtype: twilio.rest.api.v2010.account.call.notification.NotificationContext """ - super(NotificationContext, self).__init__(version) + 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): - """ - Fetch a NotificationInstance + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + self._uri = ( + "/Accounts/{account_sid}/Calls/{call_sid}/Notifications.json".format( + **self._solution + ) + ) - :returns: Fetched NotificationInstance - :rtype: twilio.rest.api.v2010.account.call.notification.NotificationInstance + 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]: """ - params = values.of({}) + 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. - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) + :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) - return NotificationInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - call_sid=self._solution['call_sid'], - sid=self._solution['sid'], + :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"], ) - def delete(self): - """ - Deletes the NotificationInstance + return self._version.stream(page, limits["limit"]) - :returns: True if delete succeeds, False otherwise - :rtype: bool + 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]: """ - return self._version.delete('delete', self._uri) + 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. - def __repr__(self): - """ - Provide a friendly representation + :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: Machine friendly representation - :rtype: str + :returns: Generator that will yield up to limit results """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class NotificationInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid, call_sid, sid=None): - """ - Initialize the NotificationInstance - - :returns: twilio.rest.api.v2010.account.call.notification.NotificationInstance - :rtype: twilio.rest.api.v2010.account.call.notification.NotificationInstance - """ - super(NotificationInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'api_version': payload['api_version'], - 'call_sid': payload['call_sid'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'error_code': payload['error_code'], - 'log': payload['log'], - 'message_date': deserialize.rfc2822_datetime(payload['message_date']), - 'message_text': payload['message_text'], - 'more_info': payload['more_info'], - 'request_method': payload['request_method'], - 'request_url': payload['request_url'], - 'sid': payload['sid'], - 'uri': payload['uri'], - 'request_variables': payload.get('request_variables'), - 'response_body': payload.get('response_body'), - 'response_headers': payload.get('response_headers'), - } + 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"], + ) - # Context - self._context = None - self._solution = { - 'account_sid': account_sid, - 'call_sid': call_sid, - 'sid': sid or self._properties['sid'], - } + return self._version.stream_async(page, limits["limit"]) - @property - def _proxy(self): + 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]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Lists NotificationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: NotificationContext for this NotificationInstance - :rtype: twilio.rest.api.v2010.account.call.notification.NotificationContext - """ - 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'], + :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, ) - return self._context + ) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + 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. - @property - def api_version(self): - """ - :returns: The api_version - :rtype: unicode + :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: """ - return self._properties['api_version'] + Retrieve a single page of NotificationInstance records from the API. + Request is executed immediately - @property - def call_sid(self): - """ - :returns: The call_sid - :rtype: unicode - """ - return self._properties['call_sid'] + :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 - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime + :returns: Page of NotificationInstance """ - return self._properties['date_created'] + 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, + } + ) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def error_code(self): - """ - :returns: The error_code - :rtype: unicode - """ - return self._properties['error_code'] + headers["Accept"] = "application/json" - @property - def log(self): - """ - :returns: The log - :rtype: unicode - """ - return self._properties['log'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NotificationPage(self._version, response, self._solution) - @property - def message_date(self): - """ - :returns: The message_date - :rtype: datetime - """ - return self._properties['message_date'] + 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 - @property - def message_text(self): - """ - :returns: The message_text - :rtype: unicode - """ - return self._properties['message_text'] + :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 - @property - def more_info(self): - """ - :returns: The more_info - :rtype: unicode + :returns: Page of NotificationInstance """ - return self._properties['more_info'] + 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, + } + ) - @property - def request_method(self): - """ - :returns: The request_method - :rtype: unicode - """ - return self._properties['request_method'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def request_url(self): - """ - :returns: The request_url - :rtype: unicode - """ - return self._properties['request_url'] + headers["Accept"] = "application/json" - @property - def request_variables(self): - """ - :returns: The request_variables - :rtype: unicode - """ - return self._properties['request_variables'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NotificationPage(self._version, response, self._solution) - @property - def response_body(self): - """ - :returns: The response_body - :rtype: unicode + def get_page(self, target_url: str) -> NotificationPage: """ - return self._properties['response_body'] + Retrieve a specific page of NotificationInstance records from the API. + Request is executed immediately - @property - def response_headers(self): - """ - :returns: The response_headers - :rtype: unicode - """ - return self._properties['response_headers'] + :param target_url: API-generated URL for the requested results page - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + :returns: Page of NotificationInstance """ - return self._properties['sid'] + response = self._version.domain.twilio.request("GET", target_url) + return NotificationPage(self._version, response, self._solution) - @property - def uri(self): + async def get_page_async(self, target_url: str) -> NotificationPage: """ - :returns: The uri - :rtype: unicode + 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 """ - return self._properties['uri'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return NotificationPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> NotificationContext: """ - Fetch a NotificationInstance + Constructs a NotificationContext - :returns: Fetched NotificationInstance - :rtype: twilio.rest.api.v2010.account.call.notification.NotificationInstance + :param sid: The Twilio-provided string that uniquely identifies the Call Notification resource to fetch. """ - return self._proxy.fetch() + return NotificationContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) - def delete(self): + def __call__(self, sid: str) -> NotificationContext: """ - Deletes the NotificationInstance + Constructs a NotificationContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the Call Notification resource to fetch. """ - return self._proxy.delete() + return NotificationContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 "".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 "".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 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 [ 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 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 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 [ 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 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 "" diff --git a/twilio/rest/api/v2010/account/call/recording.py b/twilio/rest/api/v2010/account/call/recording.py index d2a8303fef..5b93ec6c95 100644 --- a/twilio/rest/api/v2010/account/call/recording.py +++ b/twilio/rest/api/v2010/account/call/recording.py @@ -1,530 +1,822 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 RecordingList(ListResource): - """ """ - - def __init__(self, version, account_sid, call_sid): - """ - Initialize the RecordingList +class RecordingInstance(InstanceResource): - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param call_sid: The call_sid + class Source(object): + DIALVERB = "DialVerb" + CONFERENCE = "Conference" + OUTBOUNDAPI = "OutboundAPI" + TRUNKING = "Trunking" + RECORDVERB = "RecordVerb" + STARTCALLRECORDINGAPI = "StartCallRecordingAPI" + STARTCONFERENCERECORDINGAPI = "StartConferenceRecordingAPI" - :returns: twilio.rest.api.v2010.account.call.recording.RecordingList - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingList - """ - super(RecordingList, self).__init__(version) + 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") - # 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) + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid or self.sid, + } + self._context: Optional[RecordingContext] = None - def stream(self, date_created_before=values.unset, date_created=values.unset, - date_created_after=values.unset, limit=None, page_size=None): + @property + def _proxy(self) -> "RecordingContext": """ - 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. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param date date_created_before: The date_created - :param date date_created: The date_created - :param date date_created_after: The date_created - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.call.recording.RecordingInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the RecordingInstance - page = self.page( - date_created_before=date_created_before, - date_created=date_created, - date_created_after=date_created_after, - page_size=limits['page_size'], - ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, date_created_before=values.unset, date_created=values.unset, - date_created_after=values.unset, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists RecordingInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the RecordingInstance - :param date date_created_before: The date_created - :param date date_created: The date_created - :param date date_created_after: The date_created - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.call.recording.RecordingInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream( - date_created_before=date_created_before, - date_created=date_created, - date_created_after=date_created_after, - limit=limit, - page_size=page_size, - )) + return await self._proxy.delete_async() - def page(self, date_created_before=values.unset, date_created=values.unset, - date_created_after=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch(self) -> "RecordingInstance": """ - Retrieve a single page of RecordingInstance records from the API. - Request is executed immediately + Fetch the RecordingInstance - :param date date_created_before: The date_created - :param date date_created: The date_created - :param date date_created_after: The date_created - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of RecordingInstance - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingPage + :returns: The fetched RecordingInstance """ - params = values.of({ - 'DateCreated<': serialize.iso8601_date(date_created_before), - 'DateCreated': serialize.iso8601_date(date_created), - 'DateCreated>': serialize.iso8601_date(date_created_after), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + async def fetch_async(self) -> "RecordingInstance": + """ + Asynchronous coroutine to fetch the RecordingInstance - return RecordingPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched RecordingInstance """ - Retrieve a specific page of RecordingInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_async() - :param str target_url: API-generated URL for the requested results page + def update( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> "RecordingInstance": + """ + Update the RecordingInstance - :returns: Page of RecordingInstance - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingPage + :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 """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + status=status, + pause_behavior=pause_behavior, ) - return RecordingPage(self._version, response, self._solution) - - def get(self, sid): + async def update_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> "RecordingInstance": """ - Constructs a RecordingContext + Asynchronous coroutine to update the RecordingInstance - :param sid: The sid + :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: twilio.rest.api.v2010.account.call.recording.RecordingContext - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingContext + :returns: The updated RecordingInstance """ - return RecordingContext( - self._version, - account_sid=self._solution['account_sid'], - call_sid=self._solution['call_sid'], - sid=sid, + return await self._proxy.update_async( + status=status, + pause_behavior=pause_behavior, ) - def __call__(self, sid): + def __repr__(self) -> str: """ - Constructs a RecordingContext + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - :param sid: The sid +class RecordingContext(InstanceContext): - :returns: twilio.rest.api.v2010.account.call.recording.RecordingContext - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingContext + def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): """ - return RecordingContext( - self._version, - account_sid=self._solution['account_sid'], - call_sid=self._solution['call_sid'], - sid=sid, + 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 __repr__(self): + def delete(self) -> bool: """ - Provide a friendly representation + Deletes the RecordingInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class RecordingPage(Page): - """ """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, response, solution): + async def delete_async(self) -> bool: """ - Initialize the RecordingPage + Asynchronous coroutine that deletes the RecordingInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The account_sid - :param call_sid: The call_sid - :returns: twilio.rest.api.v2010.account.call.recording.RecordingPage - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingPage + :returns: True if delete succeeds, False otherwise """ - super(RecordingPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RecordingInstance: """ - Build an instance of RecordingInstance + Fetch the RecordingInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.api.v2010.account.call.recording.RecordingInstance - :rtype: twilio.rest.api.v2010.account.call.recording.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'], + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + async def fetch_async(self) -> RecordingInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the RecordingInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched RecordingInstance """ - return '' + headers = values.of({}) -class RecordingContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - def __init__(self, version, account_sid, call_sid, sid): + 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: """ - Initialize the RecordingContext + Update the RecordingInstance - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param call_sid: The call_sid - :param sid: The sid + :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: twilio.rest.api.v2010.account.call.recording.RecordingContext - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingContext + :returns: The updated RecordingInstance """ - super(RecordingContext, self).__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) + 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 + ) - def fetch(self): + 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: """ - Fetch a RecordingInstance + Asynchronous coroutine to update the RecordingInstance - :returns: Fetched RecordingInstance - :rtype: twilio.rest.api.v2010.account.call.recording.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 """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], ) - def delete(self): + def __repr__(self) -> str: """ - Deletes the RecordingInstance + Provide a friendly representation - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RecordingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RecordingInstance: """ - return self._version.delete('delete', self._uri) + Build an instance of RecordingInstance - def __repr__(self): + :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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" -class RecordingInstance(InstanceResource): - """ """ +class RecordingList(ListResource): - class Status(object): - IN_PROGRESS = "in-progress" - PAUSED = "paused" - STOPPED = "stopped" - PROCESSING = "processing" - COMPLETED = "completed" - FAILED = "failed" + def __init__(self, version: Version, account_sid: str, call_sid: str): + """ + Initialize the RecordingList - class Source(object): - DIALVERB = "DialVerb" - CONFERENCE = "Conference" - OUTBOUNDAPI = "OutboundAPI" - TRUNKING = "Trunking" - RECORDVERB = "RecordVerb" - STARTCALLRECORDINGAPI = "StartCallRecordingAPI" - STARTCONFERENCERECORDINGAPI = "StartConferenceRecordingAPI" + :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. - def __init__(self, version, payload, account_sid, call_sid, sid=None): - """ - Initialize the RecordingInstance - - :returns: twilio.rest.api.v2010.account.call.recording.RecordingInstance - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingInstance - """ - super(RecordingInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'api_version': payload['api_version'], - 'call_sid': payload['call_sid'], - 'conference_sid': payload['conference_sid'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'duration': payload['duration'], - 'sid': payload['sid'], - 'price': deserialize.decimal(payload['price']), - 'uri': payload['uri'], - 'encryption_details': payload['encryption_details'], - 'price_unit': payload['price_unit'], - 'status': payload['status'], - 'channels': deserialize.integer(payload['channels']), - 'source': payload['source'], - 'error_code': deserialize.integer(payload['error_code']), - } + """ + super().__init__(version) - # Context - self._context = None + # Path Solution self._solution = { - 'account_sid': account_sid, - 'call_sid': call_sid, - 'sid': sid or self._properties['sid'], + "account_sid": account_sid, + "call_sid": call_sid, } + self._uri = "/Accounts/{account_sid}/Calls/{call_sid}/Recordings.json".format( + **self._solution + ) - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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"}) - :returns: RecordingContext for this RecordingInstance - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingContext - """ - 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 + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + headers["Accept"] = "application/json" - @property - def api_version(self): - """ - :returns: The api_version - :rtype: unicode - """ - return self._properties['api_version'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def call_sid(self): - """ - :returns: The call_sid - :rtype: unicode - """ - return self._properties['call_sid'] + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) - @property - def conference_sid(self): - """ - :returns: The conference_sid - :rtype: unicode - """ - return self._properties['conference_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"}) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Accept"] = "application/json" - @property - def duration(self): - """ - :returns: The duration - :rtype: unicode - """ - return self._properties['duration'] + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) - @property - def price(self): - """ - :returns: The price - :rtype: unicode + 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]: """ - return self._properties['price'] + 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. - @property - def uri(self): - """ - :returns: The uri - :rtype: unicode - """ - return self._properties['uri'] + :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) - @property - def encryption_details(self): + :returns: Generator that will yield up to limit results """ - :returns: The encryption_details - :rtype: dict + 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]: """ - return self._properties['encryption_details'] + 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. - @property - def price_unit(self): + :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 """ - :returns: The price_unit - :rtype: unicode + 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]: """ - return self._properties['price_unit'] + Lists RecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def status(self): + :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]: """ - :returns: The status - :rtype: RecordingInstance.Status + 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: """ - return self._properties['status'] + Retrieve a single page of RecordingInstance records from the API. + Request is executed immediately - @property - def channels(self): + :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 """ - :returns: The channels - :rtype: unicode + 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 """ - return self._properties['channels'] + 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, + } + ) - @property - def source(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The source - :rtype: RecordingInstance.Source + 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 """ - return self._properties['source'] + response = self._version.domain.twilio.request("GET", target_url) + return RecordingPage(self._version, response, self._solution) - @property - def error_code(self): + async def get_page_async(self, target_url: str) -> RecordingPage: """ - :returns: The error_code - :rtype: unicode + 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 """ - return self._properties['error_code'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return RecordingPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> RecordingContext: """ - Fetch a RecordingInstance + Constructs a RecordingContext - :returns: Fetched RecordingInstance - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingInstance + :param sid: The Twilio-provided string that uniquely identifies the Recording resource to update. """ - return self._proxy.fetch() + return RecordingContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) - def delete(self): + def __call__(self, sid: str) -> RecordingContext: """ - Deletes the RecordingInstance + Constructs a RecordingContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the Recording resource to update. """ - return self._proxy.delete() + return RecordingContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 "".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 "".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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" 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 "".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 "" 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 "".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 "".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 "" diff --git a/twilio/rest/api/v2010/account/conference/__init__.py b/twilio/rest/api/v2010/account/conference/__init__.py index 38a1ddde26..672d9d0fea 100644 --- a/twilio/rest/api/v2010/account/conference/__init__.py +++ b/twilio/rest/api/v2010/account/conference/__init__.py @@ -1,535 +1,791 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 ConferenceList(ListResource): - """ """ +class ConferenceInstance(InstanceResource): - def __init__(self, version, account_sid): - """ - Initialize the ConferenceList + 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" - :param Version version: Version that contains the resource - :param account_sid: The unique sid that identifies this account + class Status(object): + INIT = "init" + IN_PROGRESS = "in-progress" + COMPLETED = "completed" - :returns: twilio.rest.api.v2010.account.conference.ConferenceList - :rtype: twilio.rest.api.v2010.account.conference.ConferenceList - """ - super(ConferenceList, self).__init__(version) + class UpdateStatus(object): + COMPLETED = "completed" - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Conferences.json'.format(**self._solution) + """ + :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 - def stream(self, date_created_before=values.unset, date_created=values.unset, - date_created_after=values.unset, date_updated_before=values.unset, - date_updated=values.unset, date_updated_after=values.unset, - friendly_name=values.unset, status=values.unset, limit=None, - page_size=None): + @property + def _proxy(self) -> "ConferenceContext": """ - 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. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param date date_created_before: Filter by date created - :param date date_created: Filter by date created - :param date date_created_after: Filter by date created - :param date date_updated_before: Filter by date updated - :param date date_updated: Filter by date updated - :param date date_updated_after: Filter by date updated - :param unicode friendly_name: Filter by friendly name - :param ConferenceInstance.Status status: The status of the conference - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.conference.ConferenceInstance] + def fetch(self) -> "ConferenceInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the ConferenceInstance - page = self.page( - date_created_before=date_created_before, - date_created=date_created, - date_created_after=date_created_after, - date_updated_before=date_updated_before, - date_updated=date_updated, - date_updated_after=date_updated_after, - friendly_name=friendly_name, - status=status, - page_size=limits['page_size'], - ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched ConferenceInstance + """ + return self._proxy.fetch() - def list(self, date_created_before=values.unset, date_created=values.unset, - date_created_after=values.unset, date_updated_before=values.unset, - date_updated=values.unset, date_updated_after=values.unset, - friendly_name=values.unset, status=values.unset, limit=None, - page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the ConferenceInstance - :param date date_created_before: Filter by date created - :param date date_created: Filter by date created - :param date date_created_after: Filter by date created - :param date date_updated_before: Filter by date updated - :param date date_updated: Filter by date updated - :param date date_updated_after: Filter by date updated - :param unicode friendly_name: Filter by friendly name - :param ConferenceInstance.Status status: The status of the conference - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.conference.ConferenceInstance] + :returns: The fetched ConferenceInstance """ - return list(self.stream( - date_created_before=date_created_before, - date_created=date_created, - date_created_after=date_created_after, - date_updated_before=date_updated_before, - date_updated=date_updated, - date_updated_after=date_updated_after, - friendly_name=friendly_name, - status=status, - limit=limit, - page_size=page_size, - )) + return await self._proxy.fetch_async() - def page(self, date_created_before=values.unset, date_created=values.unset, - date_created_after=values.unset, date_updated_before=values.unset, - date_updated=values.unset, date_updated_after=values.unset, - friendly_name=values.unset, status=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + 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": """ - Retrieve a single page of ConferenceInstance records from the API. - Request is executed immediately - - :param date date_created_before: Filter by date created - :param date date_created: Filter by date created - :param date date_created_after: Filter by date created - :param date date_updated_before: Filter by date updated - :param date date_updated: Filter by date updated - :param date date_updated_after: Filter by date updated - :param unicode friendly_name: Filter by friendly name - :param ConferenceInstance.Status status: The status of the conference - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + Update the ConferenceInstance - :returns: Page of ConferenceInstance - :rtype: twilio.rest.api.v2010.account.conference.ConferencePage - """ - params = values.of({ - 'DateCreated<': serialize.iso8601_date(date_created_before), - 'DateCreated': serialize.iso8601_date(date_created), - 'DateCreated>': serialize.iso8601_date(date_created_after), - 'DateUpdated<': serialize.iso8601_date(date_updated_before), - 'DateUpdated': serialize.iso8601_date(date_updated), - 'DateUpdated>': serialize.iso8601_date(date_updated_after), - 'FriendlyName': friendly_name, - 'Status': status, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + :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 ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method used to call `announce_url`. Can be: `GET` or `POST` and the default is `POST` - response = self._version.page( - 'GET', - self._uri, - params=params, + :returns: The updated ConferenceInstance + """ + return self._proxy.update( + status=status, + announce_url=announce_url, + announce_method=announce_method, ) - return ConferencePage(self._version, response, self._solution) - - def get_page(self, target_url): + 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": """ - Retrieve a specific page of ConferenceInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the ConferenceInstance - :param str target_url: API-generated URL for the requested results page + :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 ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method used to call `announce_url`. Can be: `GET` or `POST` and the default is `POST` - :returns: Page of ConferenceInstance - :rtype: twilio.rest.api.v2010.account.conference.ConferencePage + :returns: The updated ConferenceInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + status=status, + announce_url=announce_url, + announce_method=announce_method, ) - return ConferencePage(self._version, response, self._solution) - - def get(self, sid): + @property + def participants(self) -> ParticipantList: """ - Constructs a ConferenceContext - - :param sid: Fetch by unique conference Sid - - :returns: twilio.rest.api.v2010.account.conference.ConferenceContext - :rtype: twilio.rest.api.v2010.account.conference.ConferenceContext + Access the participants """ - return ConferenceContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.participants - def __call__(self, sid): + @property + def recordings(self) -> RecordingList: """ - Constructs a ConferenceContext - - :param sid: Fetch by unique conference Sid - - :returns: twilio.rest.api.v2010.account.conference.ConferenceContext - :rtype: twilio.rest.api.v2010.account.conference.ConferenceContext + Access the recordings """ - return ConferenceContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.recordings - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ConferencePage(Page): - """ """ +class ConferenceContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str, sid: str): """ - Initialize the ConferencePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The unique sid that identifies this account + Initialize the ConferenceContext - :returns: twilio.rest.api.v2010.account.conference.ConferencePage - :rtype: twilio.rest.api.v2010.account.conference.ConferencePage + :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(ConferencePage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def fetch(self) -> ConferenceInstance: """ - Build an instance of ConferenceInstance + Fetch the ConferenceInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.api.v2010.account.conference.ConferenceInstance - :rtype: twilio.rest.api.v2010.account.conference.ConferenceInstance + :returns: The fetched ConferenceInstance """ - return ConferenceInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - def __repr__(self): - """ - Provide a friendly representation + headers = values.of({}) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Accept"] = "application/json" + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) -class ConferenceContext(InstanceContext): - """ """ + return ConferenceInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - def __init__(self, version, account_sid, sid): + async def fetch_async(self) -> ConferenceInstance: """ - Initialize the ConferenceContext + Asynchronous coroutine to fetch the ConferenceInstance - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param sid: Fetch by unique conference Sid - :returns: twilio.rest.api.v2010.account.conference.ConferenceContext - :rtype: twilio.rest.api.v2010.account.conference.ConferenceContext + :returns: The fetched ConferenceInstance """ - super(ConferenceContext, self).__init__(version) - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/Conferences/{sid}.json'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - # Dependents - self._participants = None + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - def fetch(self): + 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: """ - Fetch a 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 ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method used to call `announce_url`. Can be: `GET` or `POST` and the default is `POST` - :returns: Fetched ConferenceInstance - :rtype: twilio.rest.api.v2010.account.conference.ConferenceInstance + :returns: The updated ConferenceInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def update(self, status=values.unset, announce_url=values.unset, - announce_method=values.unset): + 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: """ - Update the ConferenceInstance + Asynchronous coroutine to update the ConferenceInstance - :param ConferenceInstance.UpdateStatus status: The status - :param unicode announce_url: The announce_url - :param unicode announce_method: The announce_method + :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 ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method used to call `announce_url`. Can be: `GET` or `POST` and the default is `POST` - :returns: Updated ConferenceInstance - :rtype: twilio.rest.api.v2010.account.conference.ConferenceInstance + :returns: The updated ConferenceInstance """ - data = values.of({'Status': status, 'AnnounceUrl': announce_url, 'AnnounceMethod': announce_method, }) - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) @property - def participants(self): + def participants(self) -> ParticipantList: """ Access the participants - - :returns: twilio.rest.api.v2010.account.conference.participant.ParticipantList - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantList """ if self._participants is None: self._participants = ParticipantList( self._version, - account_sid=self._solution['account_sid'], - conference_sid=self._solution['sid'], + self._solution["account_sid"], + self._solution["sid"], ) return self._participants - def __repr__(self): + @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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ConferenceInstance(InstanceResource): - """ """ +class ConferencePage(Page): - class Status(object): - INIT = "init" - IN_PROGRESS = "in-progress" - COMPLETED = "completed" + def get_instance(self, payload: Dict[str, Any]) -> ConferenceInstance: + """ + Build an instance of ConferenceInstance - class UpdateStatus(object): - COMPLETED = "completed" + :param payload: Payload response from the API + """ + return ConferenceInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - def __init__(self, version, payload, account_sid, sid=None): + def __repr__(self) -> str: """ - Initialize the ConferenceInstance + Provide a friendly representation - :returns: twilio.rest.api.v2010.account.conference.ConferenceInstance - :rtype: twilio.rest.api.v2010.account.conference.ConferenceInstance + :returns: Machine friendly representation """ - super(ConferenceInstance, self).__init__(version) + return "" - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'api_version': payload['api_version'], - 'friendly_name': payload['friendly_name'], - 'region': payload['region'], - 'sid': payload['sid'], - 'status': payload['status'], - 'uri': payload['uri'], - 'subresource_uris': payload['subresource_uris'], - } - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } +class ConferenceList(ListResource): - @property - def _proxy(self): + def __init__(self, version: Version, account_sid: str): """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Initialize the ConferenceList - :returns: ConferenceContext for this ConferenceInstance - :rtype: twilio.rest.api.v2010.account.conference.ConferenceContext - """ - if self._context is None: - self._context = ConferenceContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + :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. - @property - def account_sid(self): - """ - :returns: The unique sid that identifies this account - :rtype: unicode """ - return self._properties['account_sid'] + super().__init__(version) - @property - def date_created(self): - """ - :returns: The date this resource was created - :rtype: datetime + # 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]: """ - return self._properties['date_created'] + 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. - @property - def date_updated(self): - """ - :returns: The date this resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + :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) - @property - def api_version(self): - """ - :returns: The api_version - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['api_version'] + 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"], + ) - @property - def friendly_name(self): - """ - :returns: A human readable description of this resource - :rtype: unicode - """ - return self._properties['friendly_name'] + 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. - @property - def region(self): - """ - :returns: The region - :rtype: unicode - """ - return self._properties['region'] + :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) - @property - def sid(self): - """ - :returns: A string that uniquely identifies this conference - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['sid'] + 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"], + ) - @property - def status(self): + 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]: """ - :returns: The status of the conference - :rtype: ConferenceInstance.Status - """ - return self._properties['status'] + Lists ConferenceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def uri(self): + :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: """ - :returns: The URI for this resource - :rtype: unicode + 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 """ - return self._properties['uri'] + 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, + } + ) - @property - def subresource_uris(self): + headers = values.of({"Content-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 """ - :returns: The subresource_uris - :rtype: unicode + 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: """ - return self._properties['subresource_uris'] + 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 - def fetch(self): + :returns: Page of ConferenceInstance """ - Fetch a ConferenceInstance + response = self._version.domain.twilio.request("GET", target_url) + return ConferencePage(self._version, response, self._solution) - :returns: Fetched ConferenceInstance - :rtype: twilio.rest.api.v2010.account.conference.ConferenceInstance + async def get_page_async(self, target_url: str) -> ConferencePage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of ConferenceInstance records from the API. + Request is executed immediately - def update(self, status=values.unset, announce_url=values.unset, - announce_method=values.unset): + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConferenceInstance """ - Update the ConferenceInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConferencePage(self._version, response, self._solution) - :param ConferenceInstance.UpdateStatus status: The status - :param unicode announce_url: The announce_url - :param unicode announce_method: The announce_method + def get(self, sid: str) -> ConferenceContext: + """ + Constructs a ConferenceContext - :returns: Updated ConferenceInstance - :rtype: twilio.rest.api.v2010.account.conference.ConferenceInstance + :param sid: The Twilio-provided string that uniquely identifies the Conference resource to update """ - return self._proxy.update(status=status, announce_url=announce_url, announce_method=announce_method, ) + return ConferenceContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - @property - def participants(self): + def __call__(self, sid: str) -> ConferenceContext: """ - Access the participants + Constructs a ConferenceContext - :returns: twilio.rest.api.v2010.account.conference.participant.ParticipantList - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantList + :param sid: The Twilio-provided string that uniquely identifies the Conference resource to update """ - return self._proxy.participants + return ConferenceContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/api/v2010/account/conference/participant.py b/twilio/rest/api/v2010/account/conference/participant.py index 7d60cd52d1..3c49e5387c 100644 --- a/twilio/rest/api/v2010/account/conference/participant.py +++ b/twilio/rest/api/v2010/account/conference/participant.py @@ -1,633 +1,1201 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 ParticipantList(ListResource): - """ """ +class ParticipantInstance(InstanceResource): - def __init__(self, version, account_sid, conference_sid): - """ - Initialize the ParticipantList + class Status(object): + QUEUED = "queued" + CONNECTING = "connecting" + RINGING = "ringing" + CONNECTED = "connected" + COMPLETE = "complete" + FAILED = "failed" - :param Version version: Version that contains the resource - :param account_sid: The unique sid that identifies this account - :param conference_sid: A string that uniquely identifies this conference + """ + :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 - :returns: twilio.rest.api.v2010.account.conference.participant.ParticipantList - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantList + @property + def _proxy(self) -> "ParticipantContext": """ - super(ParticipantList, self).__init__(version) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - # 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_, to, status_callback=values.unset, - status_callback_method=values.unset, - status_callback_event=values.unset, timeout=values.unset, - record=values.unset, muted=values.unset, beep=values.unset, - start_conference_on_enter=values.unset, - end_conference_on_exit=values.unset, wait_url=values.unset, - wait_method=values.unset, early_media=values.unset, - max_participants=values.unset, conference_record=values.unset, - conference_trim=values.unset, - conference_status_callback=values.unset, - conference_status_callback_method=values.unset, - conference_status_callback_event=values.unset, - recording_channels=values.unset, - recording_status_callback=values.unset, - recording_status_callback_method=values.unset, - sip_auth_username=values.unset, sip_auth_password=values.unset, - region=values.unset, - conference_recording_status_callback=values.unset, - conference_recording_status_callback_method=values.unset, - recording_status_callback_event=values.unset, - conference_recording_status_callback_event=values.unset): - """ - Create a new ParticipantInstance - - :param unicode from_: The from - :param unicode to: The to - :param unicode status_callback: The status_callback - :param unicode status_callback_method: The status_callback_method - :param unicode status_callback_event: The status_callback_event - :param unicode timeout: The timeout - :param bool record: The record - :param bool muted: The muted - :param unicode beep: The beep - :param bool start_conference_on_enter: The start_conference_on_enter - :param bool end_conference_on_exit: The end_conference_on_exit - :param unicode wait_url: The wait_url - :param unicode wait_method: The wait_method - :param bool early_media: The early_media - :param unicode max_participants: The max_participants - :param unicode conference_record: The conference_record - :param unicode conference_trim: The conference_trim - :param unicode conference_status_callback: The conference_status_callback - :param unicode conference_status_callback_method: The conference_status_callback_method - :param unicode conference_status_callback_event: The conference_status_callback_event - :param unicode recording_channels: The recording_channels - :param unicode recording_status_callback: The recording_status_callback - :param unicode recording_status_callback_method: The recording_status_callback_method - :param unicode sip_auth_username: The sip_auth_username - :param unicode sip_auth_password: The sip_auth_password - :param unicode region: The region - :param unicode conference_recording_status_callback: The conference_recording_status_callback - :param unicode conference_recording_status_callback_method: The conference_recording_status_callback_method - :param unicode recording_status_callback_event: The recording_status_callback_event - :param unicode conference_recording_status_callback_event: The conference_recording_status_callback_event - - :returns: Newly created ParticipantInstance - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantInstance - """ - data = values.of({ - 'From': from_, - 'To': to, - 'StatusCallback': status_callback, - 'StatusCallbackMethod': status_callback_method, - 'StatusCallbackEvent': serialize.map(status_callback_event, lambda e: e), - 'Timeout': timeout, - 'Record': record, - 'Muted': muted, - 'Beep': beep, - 'StartConferenceOnEnter': start_conference_on_enter, - 'EndConferenceOnExit': end_conference_on_exit, - 'WaitUrl': wait_url, - 'WaitMethod': wait_method, - 'EarlyMedia': 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), - }) + :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 - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + def delete(self) -> bool: + """ + Deletes the ParticipantInstance - return ParticipantInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - conference_sid=self._solution['conference_sid'], - ) - def stream(self, muted=values.unset, hold=values.unset, limit=None, - page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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: Filter by muted participants - :param bool hold: The hold - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.conference.participant.ParticipantInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the ParticipantInstance - page = self.page(muted=muted, hold=hold, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, muted=values.unset, hold=values.unset, limit=None, - page_size=None): + def fetch(self) -> "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. + Fetch the ParticipantInstance - :param bool muted: Filter by muted participants - :param bool hold: The hold - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.conference.participant.ParticipantInstance] + :returns: The fetched ParticipantInstance """ - return list(self.stream(muted=muted, hold=hold, limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, muted=values.unset, hold=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + async def fetch_async(self) -> "ParticipantInstance": """ - Retrieve a single page of ParticipantInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the ParticipantInstance - :param bool muted: Filter by muted participants - :param bool hold: The hold - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of ParticipantInstance - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantPage + :returns: The fetched ParticipantInstance """ - params = values.of({ - 'Muted': muted, - 'Hold': hold, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return await self._proxy.fetch_async() - response = self._version.page( - 'GET', - self._uri, - params=params, + 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 ``, ``, ``, or `` 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 ``, ``, ``, or `` 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 [ 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, ) - return ParticipantPage(self._version, response, self._solution) + 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 ``, ``, ``, or `` 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 ``, ``, ``, or `` 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 [ 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 get_page(self, target_url): + def __repr__(self) -> str: """ - Retrieve a specific page of ParticipantInstance records from the API. - Request is executed immediately + Provide a friendly representation - :param str target_url: API-generated URL for the requested results page + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: Page of ParticipantInstance - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantPage + +class ParticipantContext(InstanceContext): + + def __init__( + self, version: Version, account_sid: str, conference_sid: str, call_sid: str + ): """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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 ) - return ParticipantPage(self._version, response, self._solution) + def delete(self) -> bool: + """ + Deletes the ParticipantInstance + - def get(self, call_sid): + :returns: True if delete succeeds, False otherwise """ - Constructs a ParticipantContext - :param call_sid: The call_sid + headers = values.of({}) - :returns: twilio.rest.api.v2010.account.conference.participant.ParticipantContext - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantContext + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - return ParticipantContext( - self._version, - account_sid=self._solution['account_sid'], - conference_sid=self._solution['conference_sid'], - call_sid=call_sid, + 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 __call__(self, call_sid): + def fetch(self) -> ParticipantInstance: """ - Constructs a ParticipantContext + Fetch the ParticipantInstance - :param call_sid: The call_sid - :returns: twilio.rest.api.v2010.account.conference.participant.ParticipantContext - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantContext + :returns: The fetched ParticipantInstance """ - return ParticipantContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ParticipantInstance( self._version, - account_sid=self._solution['account_sid'], - conference_sid=self._solution['conference_sid'], - call_sid=call_sid, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], ) - def __repr__(self): + async def fetch_async(self) -> ParticipantInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the ParticipantInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched ParticipantInstance """ - return '' + headers = values.of({}) -class ParticipantPage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): + 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: """ - Initialize the ParticipantPage + 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 ``, ``, ``, or `` 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 ``, ``, ``, or `` 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 [ 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 ``, ``, ``, or `` 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 ``, ``, ``, or `` 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 [ 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"], + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The unique sid that identifies this account - :param conference_sid: A string that uniquely identifies this conference + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.api.v2010.account.conference.participant.ParticipantPage - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantPage + :returns: Machine friendly representation """ - super(ParticipantPage, self).__init__(version, response) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Path Solution - self._solution = solution - def get_instance(self, payload): +class ParticipantPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: """ Build an instance of ParticipantInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.conference.participant.ParticipantInstance - :rtype: twilio.rest.api.v2010.account.conference.participant.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'], + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class ParticipantContext(InstanceContext): - """ """ +class ParticipantList(ListResource): - def __init__(self, version, account_sid, conference_sid, call_sid): + def __init__(self, version: Version, account_sid: str, conference_sid: str): """ - Initialize the ParticipantContext + Initialize the ParticipantList - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param conference_sid: The string that uniquely identifies this conference - :param call_sid: The call_sid + :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. - :returns: twilio.rest.api.v2010.account.conference.participant.ParticipantContext - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantContext """ - super(ParticipantContext, self).__init__(version) + super().__init__(version) # Path Solution self._solution = { - 'account_sid': account_sid, - 'conference_sid': conference_sid, - 'call_sid': call_sid, + "account_sid": account_sid, + "conference_sid": conference_sid, } - self._uri = '/Accounts/{account_sid}/Conferences/{conference_sid}/Participants/{call_sid}.json'.format(**self._solution) + self._uri = "/Accounts/{account_sid}/Conferences/{conference_sid}/Participants.json".format( + **self._solution + ) - def fetch(self): - """ - Fetch a ParticipantInstance + 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 [ 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"}) - :returns: Fetched ParticipantInstance - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantInstance - """ - params = values.of({}) + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], - call_sid=self._solution['call_sid'], + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], ) - def update(self, muted=values.unset, hold=values.unset, hold_url=values.unset, - hold_method=values.unset, announce_url=values.unset, - announce_method=values.unset): - """ - Update the ParticipantInstance + 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 [ 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"}) - :param bool muted: Indicates if the participant should be muted - :param bool hold: The hold - :param unicode hold_url: The hold_url - :param unicode hold_method: The hold_method - :param unicode announce_url: The announce_url - :param unicode announce_method: The announce_method - - :returns: Updated ParticipantInstance - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantInstance - """ - data = values.of({ - 'Muted': muted, - 'Hold': hold, - 'HoldUrl': hold_url, - 'HoldMethod': hold_method, - 'AnnounceUrl': announce_url, - 'AnnounceMethod': announce_method, - }) + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], - call_sid=self._solution['call_sid'], + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], ) - def delete(self): - """ - Deletes the ParticipantInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool + 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]: """ - return self._version.delete('delete', self._uri) + 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. - def __repr__(self): - """ - Provide a friendly representation + :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: Machine friendly representation - :rtype: str + :returns: Generator that will yield up to limit results """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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"]) -class ParticipantInstance(InstanceResource): - """ """ + 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. - class Status(object): - QUEUED = "queued" - CONNECTING = "connecting" - RINGING = "ringing" - CONNECTED = "connected" - COMPLETE = "complete" - FAILED = "failed" + :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) - def __init__(self, version, payload, account_sid, conference_sid, - call_sid=None): - """ - Initialize the ParticipantInstance - - :returns: twilio.rest.api.v2010.account.conference.participant.ParticipantInstance - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantInstance - """ - super(ParticipantInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'call_sid': payload['call_sid'], - 'conference_sid': payload['conference_sid'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'end_conference_on_exit': payload['end_conference_on_exit'], - 'muted': payload['muted'], - 'hold': payload['hold'], - 'start_conference_on_enter': payload['start_conference_on_enter'], - 'status': payload['status'], - 'uri': payload['uri'], - } + :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"] + ) - # Context - self._context = None - self._solution = { - 'account_sid': account_sid, - 'conference_sid': conference_sid, - 'call_sid': call_sid or self._properties['call_sid'], - } + return self._version.stream_async(page, limits["limit"]) - @property - def _proxy(self): + 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]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: ParticipantContext for this ParticipantInstance - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantContext - """ - 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'], + :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, ) - return self._context + ) - @property - def account_sid(self): + 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]: """ - :returns: The unique sid that identifies this account - :rtype: unicode - """ - return self._properties['account_sid'] + 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. - @property - def call_sid(self): - """ - :returns: A string that uniquely identifies this call - :rtype: unicode + :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: """ - return self._properties['call_sid'] + Retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately - @property - def conference_sid(self): - """ - :returns: A string that uniquely identifies this conference - :rtype: unicode - """ - return self._properties['conference_sid'] + :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 - @property - def date_created(self): - """ - :returns: The date this resource was created - :rtype: datetime + :returns: Page of ParticipantInstance """ - return self._properties['date_created'] + 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, + } + ) - @property - def date_updated(self): - """ - :returns: The date this resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def end_conference_on_exit(self): - """ - :returns: Indicates if the endConferenceOnExit was set - :rtype: bool - """ - return self._properties['end_conference_on_exit'] + headers["Accept"] = "application/json" - @property - def muted(self): - """ - :returns: Indicates if the participant is muted - :rtype: bool - """ - return self._properties['muted'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) - @property - def hold(self): - """ - :returns: The hold - :rtype: bool - """ - return self._properties['hold'] + 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 - @property - def start_conference_on_enter(self): - """ - :returns: Indicates if the startConferenceOnEnter attribute was set - :rtype: bool - """ - return self._properties['start_conference_on_enter'] + :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 - @property - def status(self): - """ - :returns: The status - :rtype: ParticipantInstance.Status + :returns: Page of ParticipantInstance """ - return self._properties['status'] + 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, + } + ) - @property - def uri(self): - """ - :returns: The URI for this resource - :rtype: unicode + headers = values.of({"Content-Type": "application/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: """ - return self._properties['uri'] + Retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance """ - Fetch a ParticipantInstance + response = self._version.domain.twilio.request("GET", target_url) + return ParticipantPage(self._version, response, self._solution) - :returns: Fetched ParticipantInstance - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantInstance + async def get_page_async(self, target_url: str) -> ParticipantPage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately - def update(self, muted=values.unset, hold=values.unset, hold_url=values.unset, - hold_method=values.unset, announce_url=values.unset, - announce_method=values.unset): + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance """ - Update the ParticipantInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return ParticipantPage(self._version, response, self._solution) - :param bool muted: Indicates if the participant should be muted - :param bool hold: The hold - :param unicode hold_url: The hold_url - :param unicode hold_method: The hold_method - :param unicode announce_url: The announce_url - :param unicode announce_method: The announce_method + def get(self, call_sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext - :returns: Updated ParticipantInstance - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantInstance + :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 self._proxy.update( - muted=muted, - hold=hold, - hold_url=hold_url, - hold_method=hold_method, - announce_url=announce_url, - announce_method=announce_method, + return ParticipantContext( + self._version, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=call_sid, ) - def delete(self): + def __call__(self, call_sid: str) -> ParticipantContext: """ - Deletes the ParticipantInstance + Constructs a ParticipantContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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 self._proxy.delete() + return ParticipantContext( + self._version, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=call_sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 "".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 "".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 "" + + +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 "" diff --git a/twilio/rest/api/v2010/account/connect_app.py b/twilio/rest/api/v2010/account/connect_app.py index d2827b5c32..689a2b184a 100644 --- a/twilio/rest/api/v2010/account/connect_app.py +++ b/twilio/rest/api/v2010/account/connect_app.py @@ -1,474 +1,690 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import serialize -from twilio.base import values +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 ConnectAppList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the ConnectAppList +class ConnectAppInstance(InstanceResource): - :param Version version: Version that contains the resource - :param account_sid: The unique sid that identifies this account + class Permission(object): + GET_ALL = "get-all" + POST_ALL = "post-all" - :returns: twilio.rest.api.v2010.account.connect_app.ConnectAppList - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppList - """ - super(ConnectAppList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/ConnectApps.json'.format(**self._solution) + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[ConnectAppContext] = None - def stream(self, limit=None, page_size=None): + @property + def _proxy(self) -> "ConnectAppContext": """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.connect_app.ConnectAppInstance] + :returns: ConnectAppContext for this ConnectAppInstance """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) + if self._context is None: + self._context = ConnectAppContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - def list(self, limit=None, page_size=None): + def delete(self) -> bool: """ - Lists ConnectAppInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the ConnectAppInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.connect_app.ConnectAppInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.delete() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def delete_async(self) -> bool: """ - Retrieve a single page of ConnectAppInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the ConnectAppInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of ConnectAppInstance - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppPage + :returns: True if delete succeeds, False otherwise """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return ConnectAppPage(self._version, response, self._solution) + return await self._proxy.delete_async() - def get_page(self, target_url): + def fetch(self) -> "ConnectAppInstance": """ - Retrieve a specific page of ConnectAppInstance records from the API. - Request is executed immediately + Fetch the ConnectAppInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of ConnectAppInstance - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppPage + :returns: The fetched ConnectAppInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ConnectAppPage(self._version, response, self._solution) + return self._proxy.fetch() - def get(self, sid): + async def fetch_async(self) -> "ConnectAppInstance": """ - Constructs a ConnectAppContext + Asynchronous coroutine to fetch the ConnectAppInstance - :param sid: Fetch by unique connect-app Sid - :returns: twilio.rest.api.v2010.account.connect_app.ConnectAppContext - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppContext + :returns: The fetched ConnectAppInstance """ - return ConnectAppContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return await self._proxy.fetch_async() - def __call__(self, 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": """ - Constructs a ConnectAppContext + Update the ConnectAppInstance - :param sid: Fetch by unique connect-app Sid + :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: twilio.rest.api.v2010.account.connect_app.ConnectAppContext - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppContext + :returns: The updated ConnectAppInstance """ - return ConnectAppContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + 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, + ) - def __repr__(self): + 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 - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ConnectAppPage(Page): - """ """ +class ConnectAppContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str, sid: str): """ - Initialize the ConnectAppPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The unique sid that identifies this account + Initialize the ConnectAppContext - :returns: twilio.rest.api.v2010.account.connect_app.ConnectAppPage - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppPage + :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(ConnectAppPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/ConnectApps/{sid}.json".format( + **self._solution + ) - def get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of ConnectAppInstance + Deletes the ConnectAppInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.api.v2010.account.connect_app.ConnectAppInstance - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppInstance + :returns: True if delete succeeds, False otherwise """ - return ConnectAppInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the ConnectAppInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class ConnectAppContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, account_sid, sid): + def fetch(self) -> ConnectAppInstance: """ - Initialize the ConnectAppContext + Fetch the ConnectAppInstance - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param sid: Fetch by unique connect-app Sid - :returns: twilio.rest.api.v2010.account.connect_app.ConnectAppContext - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppContext + :returns: The fetched ConnectAppInstance """ - super(ConnectAppContext, self).__init__(version) - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/ConnectApps/{sid}.json'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - def fetch(self): + 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: """ - Fetch a ConnectAppInstance + Asynchronous coroutine to fetch the ConnectAppInstance - :returns: Fetched ConnectAppInstance - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppInstance + + :returns: The fetched ConnectAppInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def update(self, authorize_redirect_url=values.unset, company_name=values.unset, - deauthorize_callback_method=values.unset, - deauthorize_callback_url=values.unset, description=values.unset, - friendly_name=values.unset, homepage_url=values.unset, - permissions=values.unset): + 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 unicode authorize_redirect_url: URIL Twilio sends requests when users authorize - :param unicode company_name: The company name set for this Connect App. - :param unicode deauthorize_callback_method: HTTP method Twilio WIll use making requests to the url - :param unicode deauthorize_callback_url: URL Twilio will send a request when a user de-authorizes this app - :param unicode description: A more detailed human readable description - :param unicode friendly_name: A human readable name for the Connect App. - :param unicode homepage_url: The URL users can obtain more information - :param ConnectAppInstance.Permission permissions: The set of permissions that your ConnectApp requests. - - :returns: Updated ConnectAppInstance - :rtype: twilio.rest.api.v2010.account.connect_app.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), - }) + :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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) return ConnectAppInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def __repr__(self): - """ - Provide a friendly representation + 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({}) - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" -class ConnectAppInstance(InstanceResource): - """ """ + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - class Permission(object): - GET_ALL = "get-all" - POST_ALL = "post-all" + return ConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - def __init__(self, version, payload, account_sid, sid=None): + def __repr__(self) -> str: """ - Initialize the ConnectAppInstance + Provide a friendly representation - :returns: twilio.rest.api.v2010.account.connect_app.ConnectAppInstance - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppInstance + :returns: Machine friendly representation """ - super(ConnectAppInstance, self).__init__(version) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'authorize_redirect_url': payload['authorize_redirect_url'], - 'company_name': payload['company_name'], - 'deauthorize_callback_method': payload['deauthorize_callback_method'], - 'deauthorize_callback_url': payload['deauthorize_callback_url'], - 'description': payload['description'], - 'friendly_name': payload['friendly_name'], - 'homepage_url': payload['homepage_url'], - 'permissions': payload['permissions'], - 'sid': payload['sid'], - 'uri': payload['uri'], - } - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } +class ConnectAppPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> ConnectAppInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of ConnectAppInstance - :returns: ConnectAppContext for this ConnectAppInstance - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = ConnectAppContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + return ConnectAppInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def account_sid(self): + def __repr__(self) -> str: """ - :returns: The unique sid that identifies this account - :rtype: unicode - """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def authorize_redirect_url(self): - """ - :returns: URIL Twilio sends requests when users authorize - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['authorize_redirect_url'] + return "" - @property - def company_name(self): - """ - :returns: The company name set for this Connect App. - :rtype: unicode + +class ConnectAppList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - return self._properties['company_name'] + 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. - @property - def deauthorize_callback_method(self): """ - :returns: HTTP method Twilio WIll use making requests to the url - :rtype: unicode + 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]: """ - return self._properties['deauthorize_callback_method'] + 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. - @property - def deauthorize_callback_url(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: URL Twilio will send a request when a user de-authorizes this app - :rtype: unicode + 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]: """ - return self._properties['deauthorize_callback_url'] + 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. - @property - def description(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: A more detailed human readable description - :rtype: unicode + 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]: """ - return self._properties['description'] + Lists ConnectAppInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def friendly_name(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: A human readable name for the Connect App. - :rtype: unicode + 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]: """ - return self._properties['friendly_name'] + 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. - @property - def homepage_url(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The URL users can obtain more information - :rtype: unicode + 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: """ - return self._properties['homepage_url'] + Retrieve a single page of ConnectAppInstance records from the API. + Request is executed immediately - @property - def permissions(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The set of permissions that your ConnectApp requests. - :rtype: ConnectAppInstance.Permission + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['permissions'] + Asynchronously retrieve a single page of ConnectAppInstance records from the API. + Request is executed immediately - @property - def sid(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: A string that uniquely identifies this connect-apps - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['sid'] + Retrieve a specific page of ConnectAppInstance records from the API. + Request is executed immediately - @property - def uri(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConnectAppInstance """ - :returns: The URI for this resource - :rtype: unicode + 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: """ - return self._properties['uri'] + 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 - def fetch(self): + :returns: Page of ConnectAppInstance """ - Fetch a ConnectAppInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConnectAppPage(self._version, response, self._solution) - :returns: Fetched ConnectAppInstance - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppInstance + def get(self, sid: str) -> ConnectAppContext: """ - return self._proxy.fetch() + Constructs a ConnectAppContext - def update(self, authorize_redirect_url=values.unset, company_name=values.unset, - deauthorize_callback_method=values.unset, - deauthorize_callback_url=values.unset, description=values.unset, - friendly_name=values.unset, homepage_url=values.unset, - permissions=values.unset): + :param sid: The Twilio-provided string that uniquely identifies the ConnectApp resource to update. """ - Update the ConnectAppInstance + return ConnectAppContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - :param unicode authorize_redirect_url: URIL Twilio sends requests when users authorize - :param unicode company_name: The company name set for this Connect App. - :param unicode deauthorize_callback_method: HTTP method Twilio WIll use making requests to the url - :param unicode deauthorize_callback_url: URL Twilio will send a request when a user de-authorizes this app - :param unicode description: A more detailed human readable description - :param unicode friendly_name: A human readable name for the Connect App. - :param unicode homepage_url: The URL users can obtain more information - :param ConnectAppInstance.Permission permissions: The set of permissions that your ConnectApp requests. + def __call__(self, sid: str) -> ConnectAppContext: + """ + Constructs a ConnectAppContext - :returns: Updated ConnectAppInstance - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppInstance + :param sid: The Twilio-provided string that uniquely identifies the ConnectApp resource to update. """ - 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, + return ConnectAppContext( + self._version, account_sid=self._solution["account_sid"], sid=sid ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/api/v2010/account/incoming_phone_number/__init__.py b/twilio/rest/api/v2010/account/incoming_phone_number/__init__.py index 1d721f8469..c7c1eebcfd 100644 --- a/twilio/rest/api/v2010/account/incoming_phone_number/__init__.py +++ b/twilio/rest/api/v2010/account/incoming_phone_number/__init__.py @@ -1,939 +1,1310 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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.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 IncomingPhoneNumberList(ListResource): - """ """ +class IncomingPhoneNumberInstance(InstanceResource): - def __init__(self, version, account_sid): - """ - Initialize the IncomingPhoneNumberList + class AddressRequirement(object): + NONE = "none" + ANY = "any" + LOCAL = "local" + FOREIGN = "foreign" - :param Version version: Version that contains the resource - :param account_sid: The unique sid that identifies this account + class EmergencyAddressStatus(object): + REGISTERED = "registered" + UNREGISTERED = "unregistered" + PENDING_REGISTRATION = "pending-registration" + REGISTRATION_FAILURE = "registration-failure" + PENDING_UNREGISTRATION = "pending-unregistration" + UNREGISTRATION_FAILURE = "unregistration-failure" - :returns: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberList - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberList - """ - super(IncomingPhoneNumberList, self).__init__(version) + class EmergencyStatus(object): + ACTIVE = "Active" + INACTIVE = "Inactive" - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/IncomingPhoneNumbers.json'.format(**self._solution) + class VoiceReceiveMode(object): + VOICE = "voice" + FAX = "fax" - # Components - self._local = None - self._mobile = None - self._toll_free = None + """ + :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 - def stream(self, beta=values.unset, friendly_name=values.unset, - phone_number=values.unset, origin=values.unset, limit=None, - page_size=None): + @property + def _proxy(self) -> "IncomingPhoneNumberContext": """ - 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: Include new phone numbers - :param unicode friendly_name: Filter by friendly name - :param unicode phone_number: Filter by incoming phone number - :param unicode origin: The origin - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberInstance] + :returns: IncomingPhoneNumberContext for this IncomingPhoneNumberInstance """ - 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'], limits['page_limit']) + if self._context is None: + self._context = IncomingPhoneNumberContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - def list(self, beta=values.unset, friendly_name=values.unset, - phone_number=values.unset, origin=values.unset, limit=None, - page_size=None): + def delete(self) -> bool: """ - Lists IncomingPhoneNumberInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the IncomingPhoneNumberInstance - :param bool beta: Include new phone numbers - :param unicode friendly_name: Filter by friendly name - :param unicode phone_number: Filter by incoming phone number - :param unicode origin: The origin - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream( - beta=beta, - friendly_name=friendly_name, - phone_number=phone_number, - origin=origin, - limit=limit, - page_size=page_size, - )) + return self._proxy.delete() - def page(self, beta=values.unset, friendly_name=values.unset, - phone_number=values.unset, origin=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def delete_async(self) -> bool: """ - Retrieve a single page of IncomingPhoneNumberInstance records from the API. - Request is executed immediately - - :param bool beta: Include new phone numbers - :param unicode friendly_name: Filter by friendly name - :param unicode phone_number: Filter by incoming phone number - :param unicode origin: The origin - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of IncomingPhoneNumberInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberPage - """ - params = values.of({ - 'Beta': beta, - 'FriendlyName': friendly_name, - 'PhoneNumber': phone_number, - 'Origin': origin, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Asynchronous coroutine that deletes the IncomingPhoneNumberInstance - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - return IncomingPhoneNumberPage(self._version, response, self._solution) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def get_page(self, target_url): + def fetch(self) -> "IncomingPhoneNumberInstance": """ - Retrieve a specific page of IncomingPhoneNumberInstance records from the API. - Request is executed immediately + Fetch the IncomingPhoneNumberInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of IncomingPhoneNumberInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberPage + :returns: The fetched IncomingPhoneNumberInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return IncomingPhoneNumberPage(self._version, response, self._solution) + return self._proxy.fetch() - def create(self, api_version=values.unset, friendly_name=values.unset, - sms_application_sid=values.unset, sms_fallback_method=values.unset, - sms_fallback_url=values.unset, sms_method=values.unset, - sms_url=values.unset, status_callback=values.unset, - status_callback_method=values.unset, - voice_application_sid=values.unset, - voice_caller_id_lookup=values.unset, - voice_fallback_method=values.unset, voice_fallback_url=values.unset, - voice_method=values.unset, voice_url=values.unset, - emergency_status=values.unset, emergency_address_sid=values.unset, - trunk_sid=values.unset, identity_sid=values.unset, - address_sid=values.unset, phone_number=values.unset, - area_code=values.unset): - """ - Create a new IncomingPhoneNumberInstance - - :param unicode api_version: The Twilio Rest API version to use - :param unicode friendly_name: A human readable description of this resource - :param unicode sms_application_sid: Unique string that identifies the application - :param unicode sms_fallback_method: HTTP method used with sms fallback url - :param unicode sms_fallback_url: URL Twilio will request if an error occurs in executing TwiML - :param unicode sms_method: HTTP method to use with sms url - :param unicode sms_url: URL Twilio will request when receiving an SMS - :param unicode status_callback: URL Twilio will use to pass status parameters - :param unicode status_callback_method: HTTP method twilio will use with status callback - :param unicode voice_application_sid: The unique sid of the application to handle this number - :param bool voice_caller_id_lookup: Look up the caller's caller-ID - :param unicode voice_fallback_method: HTTP method used with fallback_url - :param unicode voice_fallback_url: URL Twilio will request when an error occurs in TwiML - :param unicode voice_method: HTTP method used with the voice url - :param unicode voice_url: URL Twilio will request when receiving a call - :param IncomingPhoneNumberInstance.EmergencyStatus emergency_status: The emergency_status - :param unicode emergency_address_sid: The emergency_address_sid - :param unicode trunk_sid: Unique string to identify the trunk - :param unicode identity_sid: Unique string that identifies the identity associated with number - :param unicode address_sid: Unique string that identifies the address associated with number - :param unicode phone_number: The phone number - :param unicode area_code: The desired area code for the new number - - :returns: Newly created IncomingPhoneNumberInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberInstance - """ - data = values.of({ - 'PhoneNumber': phone_number, - 'AreaCode': area_code, - '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': 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, - }) + 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 - payload = self._version.create( - 'POST', - self._uri, - data=data, + :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, ) - return IncomingPhoneNumberInstance( - self._version, - payload, - account_sid=self._solution['account_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 local(self): + def assigned_add_ons(self) -> AssignedAddOnList: """ - Access the local - - :returns: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalList - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalList + Access the assigned_add_ons """ - if self._local is None: - self._local = LocalList(self._version, account_sid=self._solution['account_sid'], ) - return self._local + return self._proxy.assigned_add_ons - @property - def mobile(self): + def __repr__(self) -> str: """ - Access the mobile + Provide a friendly representation - :returns: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileList - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileList + :returns: Machine friendly representation """ - if self._mobile is None: - self._mobile = MobileList(self._version, account_sid=self._solution['account_sid'], ) - return self._mobile + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def toll_free(self): - """ - Access the toll_free - :returns: twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreeList - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreeList +class IncomingPhoneNumberContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): """ - if self._toll_free is None: - self._toll_free = TollFreeList(self._version, account_sid=self._solution['account_sid'], ) - return self._toll_free + Initialize the IncomingPhoneNumberContext - def get(self, sid): + :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. """ - Constructs a IncomingPhoneNumberContext + super().__init__(version) - :param sid: Fetch by unique incoming-phone-number Sid + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/{sid}.json".format( + **self._solution + ) - :returns: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberContext - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberContext - """ - return IncomingPhoneNumberContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + self._assigned_add_ons: Optional[AssignedAddOnList] = None - def __call__(self, sid): + def delete(self) -> bool: """ - Constructs a IncomingPhoneNumberContext + Deletes the IncomingPhoneNumberInstance - :param sid: Fetch by unique incoming-phone-number Sid - :returns: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberContext - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberContext + :returns: True if delete succeeds, False otherwise """ - return IncomingPhoneNumberContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the IncomingPhoneNumberInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class IncomingPhoneNumberPage(Page): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> IncomingPhoneNumberInstance: """ - Initialize the IncomingPhoneNumberPage + Fetch the IncomingPhoneNumberInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The unique sid that identifies this account - :returns: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberPage - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberPage + :returns: The fetched IncomingPhoneNumberInstance """ - super(IncomingPhoneNumberPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): - """ - Build an instance of IncomingPhoneNumberInstance + headers["Accept"] = "application/json" - :param dict payload: Payload response from the API + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberInstance - """ return IncomingPhoneNumberInstance( self._version, payload, - account_sid=self._solution['account_sid'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + async def fetch_async(self) -> IncomingPhoneNumberInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the IncomingPhoneNumberInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched IncomingPhoneNumberInstance """ - return '' + headers = values.of({}) -class IncomingPhoneNumberContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, account_sid, sid): - """ - Initialize the IncomingPhoneNumberContext - - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param sid: Fetch by unique incoming-phone-number Sid + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberContext - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberContext - """ - super(IncomingPhoneNumberContext, self).__init__(version) + return IncomingPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/IncomingPhoneNumbers/{sid}.json'.format(**self._solution) - - # Dependents - self._assigned_add_ons = None - - def update(self, account_sid=values.unset, api_version=values.unset, - friendly_name=values.unset, sms_application_sid=values.unset, - sms_fallback_method=values.unset, sms_fallback_url=values.unset, - sms_method=values.unset, sms_url=values.unset, - status_callback=values.unset, status_callback_method=values.unset, - voice_application_sid=values.unset, - voice_caller_id_lookup=values.unset, - voice_fallback_method=values.unset, voice_fallback_url=values.unset, - voice_method=values.unset, voice_url=values.unset, - emergency_status=values.unset, emergency_address_sid=values.unset, - trunk_sid=values.unset, voice_receive_mode=values.unset, - identity_sid=values.unset, address_sid=values.unset): + 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 unicode account_sid: The new owner of the phone number - :param unicode api_version: The Twilio REST API version to use - :param unicode friendly_name: A human readable description of this resource - :param unicode sms_application_sid: Unique string that identifies the application - :param unicode sms_fallback_method: HTTP method used with sms fallback url - :param unicode sms_fallback_url: URL Twilio will request if an error occurs in executing TwiML - :param unicode sms_method: HTTP method to use with sms url - :param unicode sms_url: URL Twilio will request when receiving an SMS - :param unicode status_callback: URL Twilio will use to pass status parameters - :param unicode status_callback_method: HTTP method twilio will use with status callback - :param unicode voice_application_sid: The unique sid of the application to handle this number - :param bool voice_caller_id_lookup: Look up the caller's caller-ID - :param unicode voice_fallback_method: HTTP method used with fallback_url - :param unicode voice_fallback_url: URL Twilio will request when an error occurs in TwiML - :param unicode voice_method: HTTP method used with the voice url - :param unicode voice_url: URL Twilio will request when receiving a call - :param IncomingPhoneNumberInstance.EmergencyStatus emergency_status: The emergency_status - :param unicode emergency_address_sid: The emergency_address_sid - :param unicode trunk_sid: Unique string to identify the trunk - :param IncomingPhoneNumberInstance.VoiceReceiveMode voice_receive_mode: The voice_receive_mode - :param unicode identity_sid: Unique string that identifies the identity associated with number - :param unicode address_sid: Unique string that identifies the address associated with number - - :returns: Updated IncomingPhoneNumberInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.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': 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, - }) + :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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) return IncomingPhoneNumberInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def fetch(self): - """ - Fetch a IncomingPhoneNumberInstance + 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({}) - :returns: Fetched IncomingPhoneNumberInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberInstance - """ - params = values.of({}) + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def delete(self): - """ - Deletes the IncomingPhoneNumberInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - @property - def assigned_add_ons(self): + def assigned_add_ons(self) -> AssignedAddOnList: """ Access the assigned_add_ons - - :returns: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnList - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnList """ if self._assigned_add_ons is None: self._assigned_add_ons = AssignedAddOnList( self._version, - account_sid=self._solution['account_sid'], - resource_sid=self._solution['sid'], + self._solution["account_sid"], + self._solution["sid"], ) return self._assigned_add_ons - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class IncomingPhoneNumberInstance(InstanceResource): - """ """ +class IncomingPhoneNumberPage(Page): - class AddressRequirement(object): - NONE = "none" - ANY = "any" - LOCAL = "local" - FOREIGN = "foreign" + def get_instance(self, payload: Dict[str, Any]) -> IncomingPhoneNumberInstance: + """ + Build an instance of IncomingPhoneNumberInstance - class EmergencyStatus(object): - ACTIVE = "Active" - INACTIVE = "Inactive" + :param payload: Payload response from the API + """ + return IncomingPhoneNumberInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - class VoiceReceiveMode(object): - VOICE = "voice" - FAX = "fax" + def __repr__(self) -> str: + """ + Provide a friendly representation - def __init__(self, version, payload, account_sid, sid=None): - """ - Initialize the IncomingPhoneNumberInstance - - :returns: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberInstance - """ - super(IncomingPhoneNumberInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'address_sid': payload['address_sid'], - 'address_requirements': payload['address_requirements'], - 'api_version': payload['api_version'], - 'beta': payload['beta'], - 'capabilities': payload['capabilities'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'friendly_name': payload['friendly_name'], - 'identity_sid': payload['identity_sid'], - 'phone_number': payload['phone_number'], - 'origin': payload['origin'], - 'sid': payload['sid'], - 'sms_application_sid': payload['sms_application_sid'], - 'sms_fallback_method': payload['sms_fallback_method'], - 'sms_fallback_url': payload['sms_fallback_url'], - 'sms_method': payload['sms_method'], - 'sms_url': payload['sms_url'], - 'status_callback': payload['status_callback'], - 'status_callback_method': payload['status_callback_method'], - 'trunk_sid': payload['trunk_sid'], - 'uri': payload['uri'], - 'voice_application_sid': payload['voice_application_sid'], - 'voice_caller_id_lookup': payload['voice_caller_id_lookup'], - 'voice_fallback_method': payload['voice_fallback_method'], - 'voice_fallback_url': payload['voice_fallback_url'], - 'voice_method': payload['voice_method'], - 'voice_url': payload['voice_url'], - 'emergency_status': payload['emergency_status'], - 'emergency_address_sid': payload['emergency_address_sid'], - } + :returns: Machine friendly representation + """ + return "" - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context +class IncomingPhoneNumberList(ListResource): - :returns: IncomingPhoneNumberContext for this IncomingPhoneNumberInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberContext + def __init__(self, version: Version, account_sid: str): """ - if self._context is None: - self._context = IncomingPhoneNumberContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + Initialize the IncomingPhoneNumberList - @property - def account_sid(self): - """ - :returns: The unique sid that identifies this account - :rtype: unicode - """ - return self._properties['account_sid'] + :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. - @property - def address_sid(self): - """ - :returns: Unique string that identifies the address associated with number - :rtype: unicode """ - return self._properties['address_sid'] + super().__init__(version) - @property - def address_requirements(self): - """ - :returns: Indicates if the customer requires an address - :rtype: IncomingPhoneNumberInstance.AddressRequirement - """ - return self._properties['address_requirements'] + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers.json".format( + **self._solution + ) - @property - def api_version(self): - """ - :returns: The Twilio REST API version to use - :rtype: unicode - """ - return self._properties['api_version'] + 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"}) - @property - def beta(self): - """ - :returns: Indicates if the phone number is a beta number - :rtype: bool - """ - return self._properties['beta'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def capabilities(self): - """ - :returns: Indicate if a phone can receive calls or messages - :rtype: unicode - """ - return self._properties['capabilities'] + headers["Accept"] = "application/json" - @property - def date_created(self): - """ - :returns: The date this resource was created - :rtype: datetime - """ - return self._properties['date_created'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def date_updated(self): - """ - :returns: The date this resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + return IncomingPhoneNumberInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def friendly_name(self): - """ - :returns: A human readable description of this resouce - :rtype: unicode - """ - return self._properties['friendly_name'] + 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"}) - @property - def identity_sid(self): - """ - :returns: Unique string that identifies the identity associated with number - :rtype: unicode - """ - return self._properties['identity_sid'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def phone_number(self): - """ - :returns: The incoming phone number - :rtype: unicode - """ - return self._properties['phone_number'] + headers["Accept"] = "application/json" - @property - def origin(self): - """ - :returns: The origin - :rtype: unicode - """ - return self._properties['origin'] + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def sid(self): - """ - :returns: A string that uniquely identifies this resource - :rtype: unicode - """ - return self._properties['sid'] + return IncomingPhoneNumberInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def sms_application_sid(self): - """ - :returns: Unique string that identifies the application - :rtype: unicode + 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]: """ - return self._properties['sms_application_sid'] + 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. - @property - def sms_fallback_method(self): - """ - :returns: HTTP method used with sms fallback url - :rtype: unicode - """ - return self._properties['sms_fallback_method'] + :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) - @property - def sms_fallback_url(self): - """ - :returns: URL Twilio will request if an error occurs in executing TwiML - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['sms_fallback_url'] + 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"], + ) - @property - def sms_method(self): - """ - :returns: HTTP method to use with sms url - :rtype: unicode - """ - return self._properties['sms_method'] + return self._version.stream(page, limits["limit"]) - @property - def sms_url(self): - """ - :returns: URL Twilio will request when receiving an SMS - :rtype: unicode + 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]: """ - return self._properties['sms_url'] + 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. - @property - def status_callback(self): - """ - :returns: URL Twilio will use to pass status parameters - :rtype: unicode - """ - return self._properties['status_callback'] + :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) - @property - def status_callback_method(self): - """ - :returns: HTTP method twilio will use with status callback - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['status_callback_method'] + 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"], + ) - @property - def trunk_sid(self): - """ - :returns: Unique string to identify the trunk - :rtype: unicode - """ - return self._properties['trunk_sid'] + return self._version.stream_async(page, limits["limit"]) - @property - def uri(self): + 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]: """ - :returns: The URI for this resource - :rtype: unicode - """ - return self._properties['uri'] + Lists IncomingPhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def voice_application_sid(self): - """ - :returns: The unique sid of the application to handle this number - :rtype: unicode - """ - return self._properties['voice_application_sid'] + :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, + ) + ) - @property - def voice_caller_id_lookup(self): - """ - :returns: Look up the caller's caller-ID - :rtype: bool - """ - return self._properties['voice_caller_id_lookup'] + 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. - @property - def voice_fallback_method(self): - """ - :returns: HTTP method used with fallback_url - :rtype: unicode + :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: """ - return self._properties['voice_fallback_method'] + Retrieve a single page of IncomingPhoneNumberInstance records from the API. + Request is executed immediately - @property - def voice_fallback_url(self): + :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 """ - :returns: URL Twilio will request when an error occurs in TwiML - :rtype: unicode + 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 """ - return self._properties['voice_fallback_url'] + 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, + } + ) - @property - def voice_method(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: HTTP method used with the voice url - :rtype: unicode + 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 """ - return self._properties['voice_method'] + response = self._version.domain.twilio.request("GET", target_url) + return IncomingPhoneNumberPage(self._version, response, self._solution) - @property - def voice_url(self): + async def get_page_async(self, target_url: str) -> IncomingPhoneNumberPage: """ - :returns: URL Twilio will request when receiving a call - :rtype: unicode + 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 """ - return self._properties['voice_url'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return IncomingPhoneNumberPage(self._version, response, self._solution) @property - def emergency_status(self): + def local(self) -> LocalList: """ - :returns: The emergency_status - :rtype: IncomingPhoneNumberInstance.EmergencyStatus + Access the local """ - return self._properties['emergency_status'] + if self._local is None: + self._local = LocalList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._local @property - def emergency_address_sid(self): - """ - :returns: The emergency_address_sid - :rtype: unicode - """ - return self._properties['emergency_address_sid'] - - def update(self, account_sid=values.unset, api_version=values.unset, - friendly_name=values.unset, sms_application_sid=values.unset, - sms_fallback_method=values.unset, sms_fallback_url=values.unset, - sms_method=values.unset, sms_url=values.unset, - status_callback=values.unset, status_callback_method=values.unset, - voice_application_sid=values.unset, - voice_caller_id_lookup=values.unset, - voice_fallback_method=values.unset, voice_fallback_url=values.unset, - voice_method=values.unset, voice_url=values.unset, - emergency_status=values.unset, emergency_address_sid=values.unset, - trunk_sid=values.unset, voice_receive_mode=values.unset, - identity_sid=values.unset, address_sid=values.unset): + def mobile(self) -> MobileList: """ - Update the IncomingPhoneNumberInstance - - :param unicode account_sid: The new owner of the phone number - :param unicode api_version: The Twilio REST API version to use - :param unicode friendly_name: A human readable description of this resource - :param unicode sms_application_sid: Unique string that identifies the application - :param unicode sms_fallback_method: HTTP method used with sms fallback url - :param unicode sms_fallback_url: URL Twilio will request if an error occurs in executing TwiML - :param unicode sms_method: HTTP method to use with sms url - :param unicode sms_url: URL Twilio will request when receiving an SMS - :param unicode status_callback: URL Twilio will use to pass status parameters - :param unicode status_callback_method: HTTP method twilio will use with status callback - :param unicode voice_application_sid: The unique sid of the application to handle this number - :param bool voice_caller_id_lookup: Look up the caller's caller-ID - :param unicode voice_fallback_method: HTTP method used with fallback_url - :param unicode voice_fallback_url: URL Twilio will request when an error occurs in TwiML - :param unicode voice_method: HTTP method used with the voice url - :param unicode voice_url: URL Twilio will request when receiving a call - :param IncomingPhoneNumberInstance.EmergencyStatus emergency_status: The emergency_status - :param unicode emergency_address_sid: The emergency_address_sid - :param unicode trunk_sid: Unique string to identify the trunk - :param IncomingPhoneNumberInstance.VoiceReceiveMode voice_receive_mode: The voice_receive_mode - :param unicode identity_sid: Unique string that identifies the identity associated with number - :param unicode address_sid: Unique string that identifies the address associated with number - - :returns: Updated IncomingPhoneNumberInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberInstance + Access the mobile """ - 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, - ) + if self._mobile is None: + self._mobile = MobileList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._mobile - def fetch(self): + @property + def toll_free(self) -> TollFreeList: """ - Fetch a IncomingPhoneNumberInstance - - :returns: Fetched IncomingPhoneNumberInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberInstance + Access the toll_free """ - return self._proxy.fetch() + if self._toll_free is None: + self._toll_free = TollFreeList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._toll_free - def delete(self): + def get(self, sid: str) -> IncomingPhoneNumberContext: """ - Deletes the IncomingPhoneNumberInstance + Constructs a IncomingPhoneNumberContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the IncomingPhoneNumber resource to update. """ - return self._proxy.delete() + return IncomingPhoneNumberContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - @property - def assigned_add_ons(self): + def __call__(self, sid: str) -> IncomingPhoneNumberContext: """ - Access the assigned_add_ons + Constructs a IncomingPhoneNumberContext - :returns: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnList - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnList + :param sid: The Twilio-provided string that uniquely identifies the IncomingPhoneNumber resource to update. """ - return self._proxy.assigned_add_ons + return IncomingPhoneNumberContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 index a8a0649073..52fe2a52af 100644 --- 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 @@ -1,496 +1,602 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 +from twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension import ( + AssignedAddOnExtensionList, +) -class AssignedAddOnList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +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 - def __init__(self, version, account_sid, resource_sid): + @property + def _proxy(self) -> "AssignedAddOnContext": """ - Initialize the AssignedAddOnList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param account_sid: The Account id that has installed this Add-on - :param resource_sid: The Phone Number id that has installed this Add-on + :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 - :returns: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnList - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnList + def delete(self) -> bool: """ - super(AssignedAddOnList, self).__init__(version) + Deletes the AssignedAddOnInstance - # 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 stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the AssignedAddOnInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the AssignedAddOnInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnInstance] + :returns: The fetched AssignedAddOnInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_async(self) -> "AssignedAddOnInstance": """ - Retrieve a single page of AssignedAddOnInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the AssignedAddOnInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of AssignedAddOnInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnPage + :returns: The fetched AssignedAddOnInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_async() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + @property + def extensions(self) -> AssignedAddOnExtensionList: + """ + Access the extensions + """ + return self._proxy.extensions - return AssignedAddOnPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get_page(self, target_url): + :returns: Machine friendly representation """ - Retrieve a specific page of AssignedAddOnInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param str target_url: API-generated URL for the requested results page - :returns: Page of AssignedAddOnInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnPage +class AssignedAddOnContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, resource_sid: str, sid: str): """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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 ) - return AssignedAddOnPage(self._version, response, self._solution) + self._extensions: Optional[AssignedAddOnExtensionList] = None - def create(self, installed_add_on_sid): + def delete(self) -> bool: """ - Create a new AssignedAddOnInstance + Deletes the AssignedAddOnInstance - :param unicode installed_add_on_sid: A string that uniquely identifies the Add-on installation - :returns: Newly created AssignedAddOnInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({'InstalledAddOnSid': installed_add_on_sid, }) - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + headers = values.of({}) - return AssignedAddOnInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - resource_sid=self._solution['resource_sid'], - ) + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def get(self, sid): + async def delete_async(self) -> bool: """ - Constructs a AssignedAddOnContext + Asynchronous coroutine that deletes the AssignedAddOnInstance - :param sid: The unique Installed Add-on Sid - :returns: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnContext - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnContext + :returns: True if delete succeeds, False otherwise """ - return AssignedAddOnContext( - self._version, - account_sid=self._solution['account_sid'], - resource_sid=self._solution['resource_sid'], - sid=sid, + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers ) - def __call__(self, sid): + def fetch(self) -> AssignedAddOnInstance: """ - Constructs a AssignedAddOnContext + Fetch the AssignedAddOnInstance - :param sid: The unique Installed Add-on Sid - :returns: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnContext - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnContext + :returns: The fetched AssignedAddOnInstance """ - return AssignedAddOnContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AssignedAddOnInstance( self._version, - account_sid=self._solution['account_sid'], - resource_sid=self._solution['resource_sid'], - sid=sid, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + async def fetch_async(self) -> AssignedAddOnInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the AssignedAddOnInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched AssignedAddOnInstance """ - return '' + headers = values.of({}) -class AssignedAddOnPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): + 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: """ - Initialize the AssignedAddOnPage + 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 - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The Account id that has installed this Add-on - :param resource_sid: The Phone Number id that has installed this Add-on + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnPage - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnPage + :returns: Machine friendly representation """ - super(AssignedAddOnPage, self).__init__(version, response) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Path Solution - self._solution = solution - def get_instance(self, payload): +class AssignedAddOnPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AssignedAddOnInstance: """ Build an instance of AssignedAddOnInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.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'], + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class AssignedAddOnContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class AssignedAddOnList(ListResource): - def __init__(self, version, account_sid, resource_sid, sid): + def __init__(self, version: Version, account_sid: str, resource_sid: str): """ - Initialize the AssignedAddOnContext + Initialize the AssignedAddOnList - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param resource_sid: The resource_sid - :param sid: The unique Installed Add-on Sid + :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. - :returns: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnContext - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnContext """ - super(AssignedAddOnContext, self).__init__(version) + 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) - - # Dependents - self._extensions = None + self._solution = { + "account_sid": account_sid, + "resource_sid": resource_sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/{resource_sid}/AssignedAddOns.json".format( + **self._solution + ) - def fetch(self): + def create(self, installed_add_on_sid: str) -> AssignedAddOnInstance: """ - Fetch a AssignedAddOnInstance + Create the AssignedAddOnInstance - :returns: Fetched AssignedAddOnInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnInstance + :param installed_add_on_sid: The SID that identifies the Add-on installation. + + :returns: The created AssignedAddOnInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], ) - def delete(self): + async def create_async(self, installed_add_on_sid: str) -> AssignedAddOnInstance: """ - Deletes the AssignedAddOnInstance + Asynchronously create the AssignedAddOnInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :param installed_add_on_sid: The SID that identifies the Add-on installation. - @property - def extensions(self): + :returns: The created AssignedAddOnInstance """ - Access the extensions - :returns: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionList - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionList + 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]: """ - if self._extensions is None: - self._extensions = AssignedAddOnExtensionList( - self._version, - account_sid=self._solution['account_sid'], - resource_sid=self._solution['resource_sid'], - assigned_add_on_sid=self._solution['sid'], - ) - return self._extensions + 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. - def __repr__(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - Provide a friendly representation + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - :returns: Machine friendly representation - :rtype: str + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AssignedAddOnInstance]: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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) -class AssignedAddOnInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, payload, account_sid, resource_sid, sid=None): - """ - Initialize the AssignedAddOnInstance - - :returns: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnInstance - """ - super(AssignedAddOnInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'resource_sid': payload['resource_sid'], - 'friendly_name': payload['friendly_name'], - 'description': payload['description'], - 'configuration': payload['configuration'], - 'unique_name': payload['unique_name'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'uri': payload['uri'], - 'subresource_uris': payload['subresource_uris'], - } + :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"]) - # Context - self._context = None - self._solution = { - 'account_sid': account_sid, - 'resource_sid': resource_sid, - 'sid': sid or self._properties['sid'], - } + return self._version.stream_async(page, limits["limit"]) - @property - def _proxy(self): + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssignedAddOnInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Lists AssignedAddOnInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: AssignedAddOnContext for this AssignedAddOnInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnContext + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - 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 list( + self.stream( + limit=limit, + page_size=page_size, ) - return self._context + ) - @property - def sid(self): - """ - :returns: A string that uniquely identifies this assigned Add-on installation - :rtype: unicode + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssignedAddOnInstance]: """ - return self._properties['sid'] + 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. - @property - def account_sid(self): - """ - :returns: The Account id that has installed this Add-on - :rtype: unicode - """ - return self._properties['account_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) - @property - def resource_sid(self): - """ - :returns: The Phone Number id that has installed this Add-on - :rtype: unicode + :returns: list that will contain up to limit results """ - return self._properties['resource_sid'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def friendly_name(self): + 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: """ - :returns: A description of this Add-on installation - :rtype: unicode - """ - return self._properties['friendly_name'] + Retrieve a single page of AssignedAddOnInstance records from the API. + Request is executed immediately - @property - def description(self): - """ - :returns: A short description of the Add-on functionality - :rtype: unicode - """ - return self._properties['description'] + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - @property - def configuration(self): - """ - :returns: The JSON object representing the current configuration - :rtype: dict + :returns: Page of AssignedAddOnInstance """ - return self._properties['configuration'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def unique_name(self): - """ - :returns: The string that uniquely identifies this Add-on installation - :rtype: unicode - """ - return self._properties['unique_name'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def date_created(self): - """ - :returns: The date this Add-on was installed - :rtype: datetime - """ - return self._properties['date_created'] + headers["Accept"] = "application/json" - @property - def date_updated(self): - """ - :returns: The date this Add-on installation was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssignedAddOnPage(self._version, response, self._solution) - @property - def uri(self): + 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: """ - :returns: The uri - :rtype: unicode + 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 """ - return self._properties['uri'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def subresource_uris(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The subresource_uris - :rtype: unicode + 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 """ - return self._properties['subresource_uris'] + response = self._version.domain.twilio.request("GET", target_url) + return AssignedAddOnPage(self._version, response, self._solution) - def fetch(self): + async def get_page_async(self, target_url: str) -> AssignedAddOnPage: """ - Fetch a AssignedAddOnInstance + 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: Fetched AssignedAddOnInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnInstance + :returns: Page of AssignedAddOnInstance """ - return self._proxy.fetch() + response = await self._version.domain.twilio.request_async("GET", target_url) + return AssignedAddOnPage(self._version, response, self._solution) - def delete(self): + def get(self, sid: str) -> AssignedAddOnContext: """ - Deletes the AssignedAddOnInstance + Constructs a AssignedAddOnContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the resource to fetch. """ - return self._proxy.delete() + return AssignedAddOnContext( + self._version, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + sid=sid, + ) - @property - def extensions(self): + def __call__(self, sid: str) -> AssignedAddOnContext: """ - Access the extensions + Constructs a AssignedAddOnContext - :returns: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionList - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionList + :param sid: The Twilio-provided string that uniquely identifies the resource to fetch. """ - return self._proxy.extensions + return AssignedAddOnContext( + self._version, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 index 9b0937ea05..1a7d9cdc34 100644 --- 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 @@ -1,424 +1,484 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 AssignedAddOnExtensionList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, account_sid, resource_sid, assigned_add_on_sid): - """ - Initialize the AssignedAddOnExtensionList - - :param Version version: Version that contains the resource - :param account_sid: The Account id that has installed this Add-on - :param resource_sid: The Phone Number id that has installed this Add-on - :param assigned_add_on_sid: A string that uniquely identifies the assigned Add-on installation - - :returns: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionList - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionList - """ - super(AssignedAddOnExtensionList, self).__init__(version) +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") - # Path Solution self._solution = { - 'account_sid': account_sid, - 'resource_sid': resource_sid, - 'assigned_add_on_sid': assigned_add_on_sid, + "account_sid": account_sid, + "resource_sid": resource_sid, + "assigned_add_on_sid": assigned_add_on_sid, + "sid": sid or self.sid, } - self._uri = '/Accounts/{account_sid}/IncomingPhoneNumbers/{resource_sid}/AssignedAddOns/{assigned_add_on_sid}/Extensions.json'.format(**self._solution) + self._context: Optional[AssignedAddOnExtensionContext] = None - def stream(self, limit=None, page_size=None): + @property + def _proxy(self) -> "AssignedAddOnExtensionContext": """ - 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. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionInstance] + def fetch(self) -> "AssignedAddOnExtensionInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the AssignedAddOnExtensionInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched AssignedAddOnExtensionInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the AssignedAddOnExtensionInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionInstance] + :returns: The fetched AssignedAddOnExtensionInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def __repr__(self) -> str: """ - Retrieve a single page of AssignedAddOnExtensionInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + Provide a friendly representation - :returns: Page of AssignedAddOnExtensionInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionPage + :returns: Machine friendly representation """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - return AssignedAddOnExtensionPage(self._version, response, self._solution) +class AssignedAddOnExtensionContext(InstanceContext): - def get_page(self, target_url): + def __init__( + self, + version: Version, + account_sid: str, + resource_sid: str, + assigned_add_on_sid: str, + sid: str, + ): """ - Retrieve a specific page of AssignedAddOnExtensionInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page + Initialize the AssignedAddOnExtensionContext - :returns: Page of AssignedAddOnExtensionInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionPage + :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. """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + super().__init__(version) - return AssignedAddOnExtensionPage(self._version, response, self._solution) + # 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 get(self, sid): + def fetch(self) -> AssignedAddOnExtensionInstance: """ - Constructs a AssignedAddOnExtensionContext + Fetch the AssignedAddOnExtensionInstance - :param sid: The unique Extension Sid - :returns: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionContext - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionContext + :returns: The fetched AssignedAddOnExtensionInstance """ - return AssignedAddOnExtensionContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AssignedAddOnExtensionInstance( 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, + 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 __call__(self, sid): + async def fetch_async(self) -> AssignedAddOnExtensionInstance: """ - Constructs a AssignedAddOnExtensionContext + Asynchronous coroutine to fetch the AssignedAddOnExtensionInstance - :param sid: The unique Extension Sid - :returns: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionContext - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionContext + :returns: The fetched AssignedAddOnExtensionInstance """ - return AssignedAddOnExtensionContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AssignedAddOnExtensionInstance( 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, + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) class AssignedAddOnExtensionPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, response, solution): - """ - Initialize the AssignedAddOnExtensionPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The Account id that has installed this Add-on - :param resource_sid: The Phone Number id that has installed this Add-on - :param assigned_add_on_sid: A string that uniquely identifies the assigned Add-on installation - - :returns: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionPage - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionPage - """ - super(AssignedAddOnExtensionPage, self).__init__(version, response) - # Path Solution - self._solution = solution - - def get_instance(self, payload): + def get_instance(self, payload: Dict[str, Any]) -> AssignedAddOnExtensionInstance: """ Build an instance of AssignedAddOnExtensionInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.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'], + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class AssignedAddOnExtensionContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class AssignedAddOnExtensionList(ListResource): - def __init__(self, version, account_sid, resource_sid, assigned_add_on_sid, - sid): + def __init__( + self, + version: Version, + account_sid: str, + resource_sid: str, + assigned_add_on_sid: str, + ): """ - Initialize the AssignedAddOnExtensionContext + Initialize the AssignedAddOnExtensionList - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param resource_sid: The resource_sid - :param assigned_add_on_sid: The assigned_add_on_sid - :param sid: The unique Extension Sid + :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. - :returns: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionContext - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionContext """ - super(AssignedAddOnExtensionContext, self).__init__(version) + 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, + "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/{sid}.json'.format(**self._solution) - - def fetch(self): - """ - Fetch a AssignedAddOnExtensionInstance + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/{resource_sid}/AssignedAddOns/{assigned_add_on_sid}/Extensions.json".format( + **self._solution + ) - :returns: Fetched AssignedAddOnExtensionInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionInstance + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AssignedAddOnExtensionInstance]: """ - params = values.of({}) + 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. - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - 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): + :returns: Generator that will yield up to limit results """ - Provide a friendly representation + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - :returns: Machine friendly representation - :rtype: str + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AssignedAddOnExtensionInstance]: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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) -class AssignedAddOnExtensionInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, payload, account_sid, resource_sid, - assigned_add_on_sid, sid=None): - """ - Initialize the AssignedAddOnExtensionInstance - - :returns: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionInstance - """ - super(AssignedAddOnExtensionInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'resource_sid': payload['resource_sid'], - 'assigned_add_on_sid': payload['assigned_add_on_sid'], - 'friendly_name': payload['friendly_name'], - 'product_name': payload['product_name'], - 'unique_name': payload['unique_name'], - 'uri': payload['uri'], - 'enabled': payload['enabled'], - } + :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"]) - # Context - self._context = None - self._solution = { - 'account_sid': account_sid, - 'resource_sid': resource_sid, - 'assigned_add_on_sid': assigned_add_on_sid, - 'sid': sid or self._properties['sid'], - } + return self._version.stream_async(page, limits["limit"]) - @property - def _proxy(self): + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssignedAddOnExtensionInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Lists AssignedAddOnExtensionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: AssignedAddOnExtensionContext for this AssignedAddOnExtensionInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionContext + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - 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 list( + self.stream( + limit=limit, + page_size=page_size, ) - return self._context + ) - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Extension - :rtype: unicode + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssignedAddOnExtensionInstance]: """ - return self._properties['sid'] + 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. - @property - def account_sid(self): - """ - :returns: The Account id that has installed this Add-on - :rtype: unicode - """ - return self._properties['account_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) - @property - def resource_sid(self): + :returns: list that will contain up to limit results """ - :returns: The Phone Number id that has installed this Add-on - :rtype: unicode - """ - return self._properties['resource_sid'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def assigned_add_on_sid(self): + 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: """ - :returns: A string that uniquely identifies the assigned Add-on installation - :rtype: unicode - """ - return self._properties['assigned_add_on_sid'] + Retrieve a single page of AssignedAddOnExtensionInstance records from the API. + Request is executed immediately - @property - def friendly_name(self): - """ - :returns: A human-readable description of this Extension - :rtype: unicode + :param page_token: PageToken provided by the API + :param page_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 """ - return self._properties['friendly_name'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def product_name(self): + headers = values.of({"Content-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: """ - :returns: A human-readable description of the Extension's Product - :rtype: unicode + 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 """ - return self._properties['product_name'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def unique_name(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The string that uniquely identifies this Extension - :rtype: unicode + 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 """ - return self._properties['unique_name'] + response = self._version.domain.twilio.request("GET", target_url) + return AssignedAddOnExtensionPage(self._version, response, self._solution) - @property - def uri(self): + async def get_page_async(self, target_url: str) -> AssignedAddOnExtensionPage: """ - :returns: The uri - :rtype: unicode + 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 """ - return self._properties['uri'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return AssignedAddOnExtensionPage(self._version, response, self._solution) - @property - def enabled(self): + def get(self, sid: str) -> AssignedAddOnExtensionContext: """ - :returns: A Boolean indicating if the Extension will be invoked - :rtype: bool + Constructs a AssignedAddOnExtensionContext + + :param sid: The Twilio-provided string that uniquely identifies the resource to fetch. """ - return self._properties['enabled'] + 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 fetch(self): + def __call__(self, sid: str) -> AssignedAddOnExtensionContext: """ - Fetch a AssignedAddOnExtensionInstance + Constructs a AssignedAddOnExtensionContext - :returns: Fetched AssignedAddOnExtensionInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionInstance + :param sid: The Twilio-provided string that uniquely identifies the resource to fetch. """ - return self._proxy.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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/api/v2010/account/incoming_phone_number/local.py b/twilio/rest/api/v2010/account/incoming_phone_number/local.py index 719f03954e..af67fb0a2d 100644 --- a/twilio/rest/api/v2010/account/incoming_phone_number/local.py +++ b/twilio/rest/api/v2010/account/incoming_phone_number/local.py @@ -1,554 +1,672 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 LocalList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the LocalList - - :param Version version: Version that contains the resource - :param account_sid: The unique sid that identifies this account - - :returns: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalList - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalList - """ - super(LocalList, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/IncomingPhoneNumbers/Local.json'.format(**self._solution) - - def stream(self, beta=values.unset, friendly_name=values.unset, - phone_number=values.unset, origin=values.unset, limit=None, - page_size=None): - """ - 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: The beta - :param unicode friendly_name: The friendly_name - :param unicode phone_number: The phone_number - :param unicode origin: The origin - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) +class LocalInstance(InstanceResource): - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.incoming_phone_number.local.LocalInstance] - """ - limits = self._version.read_limits(limit, page_size) + class AddressRequirement(object): + NONE = "none" + ANY = "any" + LOCAL = "local" + FOREIGN = "foreign" - page = self.page( - beta=beta, - friendly_name=friendly_name, - phone_number=phone_number, - origin=origin, - page_size=limits['page_size'], + 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, + } - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, beta=values.unset, friendly_name=values.unset, - phone_number=values.unset, origin=values.unset, limit=None, - page_size=None): - """ - 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: The beta - :param unicode friendly_name: The friendly_name - :param unicode phone_number: The phone_number - :param unicode origin: The origin - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.incoming_phone_number.local.LocalInstance] + def __repr__(self) -> str: """ - return list(self.stream( - beta=beta, - friendly_name=friendly_name, - phone_number=phone_number, - origin=origin, - limit=limit, - page_size=page_size, - )) - - def page(self, beta=values.unset, friendly_name=values.unset, - phone_number=values.unset, origin=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of LocalInstance records from the API. - Request is executed immediately - - :param bool beta: The beta - :param unicode friendly_name: The friendly_name - :param unicode phone_number: The phone_number - :param unicode origin: The origin - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + Provide a friendly representation - :returns: Page of LocalInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalPage + :returns: Machine friendly representation """ - params = values.of({ - 'Beta': beta, - 'FriendlyName': friendly_name, - 'PhoneNumber': phone_number, - 'Origin': origin, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - return LocalPage(self._version, response, self._solution) +class LocalPage(Page): - def get_page(self, target_url): + def get_instance(self, payload: Dict[str, Any]) -> LocalInstance: """ - Retrieve a specific page of LocalInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page + Build an instance of LocalInstance - :returns: Page of LocalInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalPage + :param payload: Payload response from the API """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return LocalInstance( + self._version, payload, account_sid=self._solution["account_sid"] ) - return LocalPage(self._version, response, self._solution) - - def create(self, phone_number, api_version=values.unset, - friendly_name=values.unset, sms_application_sid=values.unset, - sms_fallback_method=values.unset, sms_fallback_url=values.unset, - sms_method=values.unset, sms_url=values.unset, - status_callback=values.unset, status_callback_method=values.unset, - voice_application_sid=values.unset, - voice_caller_id_lookup=values.unset, - voice_fallback_method=values.unset, voice_fallback_url=values.unset, - voice_method=values.unset, voice_url=values.unset, - identity_sid=values.unset, address_sid=values.unset): - """ - Create a new LocalInstance - - :param unicode phone_number: The phone_number - :param unicode api_version: The api_version - :param unicode friendly_name: The friendly_name - :param unicode sms_application_sid: The sms_application_sid - :param unicode sms_fallback_method: The sms_fallback_method - :param unicode sms_fallback_url: The sms_fallback_url - :param unicode sms_method: The sms_method - :param unicode sms_url: The sms_url - :param unicode status_callback: The status_callback - :param unicode status_callback_method: The status_callback_method - :param unicode voice_application_sid: The voice_application_sid - :param bool voice_caller_id_lookup: The voice_caller_id_lookup - :param unicode voice_fallback_method: The voice_fallback_method - :param unicode voice_fallback_url: The voice_fallback_url - :param unicode voice_method: The voice_method - :param unicode voice_url: The voice_url - :param unicode identity_sid: The identity_sid - :param unicode address_sid: The address_sid - - :returns: Newly created LocalInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.local.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': voice_caller_id_lookup, - 'VoiceFallbackMethod': voice_fallback_method, - 'VoiceFallbackUrl': voice_fallback_url, - 'VoiceMethod': voice_method, - 'VoiceUrl': voice_url, - 'IdentitySid': identity_sid, - 'AddressSid': address_sid, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return LocalInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class LocalPage(Page): - """ """ +class LocalList(ListResource): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str): """ - Initialize the LocalPage + Initialize the LocalList - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The unique sid that identifies this account + :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. - :returns: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalPage - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalPage """ - super(LocalPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/Local.json".format( + **self._solution + ) - def get_instance(self, payload): - """ - Build an instance of LocalInstance + 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"}) - :param dict payload: Payload response from the API + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalInstance - """ - return LocalInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + headers["Accept"] = "application/json" - def __repr__(self): - """ - Provide a friendly representation + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: Machine friendly representation - :rtype: str - """ - return '' + 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"}) -class LocalInstance(InstanceResource): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - class AddressRequirement(object): - NONE = "none" - ANY = "any" - LOCAL = "local" - FOREIGN = "foreign" + headers["Accept"] = "application/json" - def __init__(self, version, payload, account_sid): - """ - Initialize the LocalInstance - - :returns: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalInstance - """ - super(LocalInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'address_sid': payload['address_sid'], - 'address_requirements': payload['address_requirements'], - 'api_version': payload['api_version'], - 'beta': payload['beta'], - 'capabilities': payload['capabilities'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'friendly_name': payload['friendly_name'], - 'identity_sid': payload['identity_sid'], - 'phone_number': payload['phone_number'], - 'origin': payload['origin'], - 'sid': payload['sid'], - 'sms_application_sid': payload['sms_application_sid'], - 'sms_fallback_method': payload['sms_fallback_method'], - 'sms_fallback_url': payload['sms_fallback_url'], - 'sms_method': payload['sms_method'], - 'sms_url': payload['sms_url'], - 'status_callback': payload['status_callback'], - 'status_callback_method': payload['status_callback_method'], - 'trunk_sid': payload['trunk_sid'], - 'uri': payload['uri'], - 'voice_application_sid': payload['voice_application_sid'], - 'voice_caller_id_lookup': payload['voice_caller_id_lookup'], - 'voice_fallback_method': payload['voice_fallback_method'], - 'voice_fallback_url': payload['voice_fallback_url'], - 'voice_method': payload['voice_method'], - 'voice_url': payload['voice_url'], - } + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + return LocalInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + 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]: """ - return self._properties['account_sid'] + 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. - @property - def address_sid(self): - """ - :returns: The address_sid - :rtype: unicode - """ - return self._properties['address_sid'] + :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) - @property - def address_requirements(self): - """ - :returns: The address_requirements - :rtype: LocalInstance.AddressRequirement + :returns: Generator that will yield up to limit results """ - return self._properties['address_requirements'] + 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"], + ) - @property - def api_version(self): - """ - :returns: The api_version - :rtype: unicode - """ - return self._properties['api_version'] + return self._version.stream(page, limits["limit"]) - @property - def beta(self): - """ - :returns: The beta - :rtype: bool + 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]: """ - return self._properties['beta'] + 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. - @property - def capabilities(self): - """ - :returns: The capabilities - :rtype: unicode - """ - return self._properties['capabilities'] + :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) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime + :returns: Generator that will yield up to limit results """ - return self._properties['date_created'] + 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"], + ) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + return self._version.stream_async(page, limits["limit"]) - @property - def friendly_name(self): + 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]: """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] + Lists LocalInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def identity_sid(self): - """ - :returns: The identity_sid - :rtype: unicode - """ - return self._properties['identity_sid'] + :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, + ) + ) - @property - def phone_number(self): - """ - :returns: The phone_number - :rtype: unicode - """ - return self._properties['phone_number'] + 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. - @property - def origin(self): + :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: """ - :returns: The origin - :rtype: unicode - """ - return self._properties['origin'] + Retrieve a single page of LocalInstance records from the API. + Request is executed immediately - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + :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 - @property - def sms_application_sid(self): - """ - :returns: The sms_application_sid - :rtype: unicode + :returns: Page of LocalInstance """ - return self._properties['sms_application_sid'] + 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, + } + ) - @property - def sms_fallback_method(self): - """ - :returns: The sms_fallback_method - :rtype: unicode - """ - return self._properties['sms_fallback_method'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def sms_fallback_url(self): - """ - :returns: The sms_fallback_url - :rtype: unicode - """ - return self._properties['sms_fallback_url'] + headers["Accept"] = "application/json" - @property - def sms_method(self): - """ - :returns: The sms_method - :rtype: unicode - """ - return self._properties['sms_method'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LocalPage(self._version, response, self._solution) - @property - def sms_url(self): - """ - :returns: The sms_url - :rtype: unicode - """ - return self._properties['sms_url'] + 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 - @property - def status_callback(self): - """ - :returns: The status_callback - :rtype: unicode - """ - return self._properties['status_callback'] + :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 - @property - def status_callback_method(self): - """ - :returns: The status_callback_method - :rtype: unicode + :returns: Page of LocalInstance """ - return self._properties['status_callback_method'] + 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, + } + ) - @property - def trunk_sid(self): - """ - :returns: The trunk_sid - :rtype: unicode - """ - return self._properties['trunk_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def uri(self): - """ - :returns: The uri - :rtype: unicode - """ - return self._properties['uri'] + headers["Accept"] = "application/json" - @property - def voice_application_sid(self): - """ - :returns: The voice_application_sid - :rtype: unicode - """ - return self._properties['voice_application_sid'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LocalPage(self._version, response, self._solution) - @property - def voice_caller_id_lookup(self): - """ - :returns: The voice_caller_id_lookup - :rtype: bool + def get_page(self, target_url: str) -> LocalPage: """ - return self._properties['voice_caller_id_lookup'] + Retrieve a specific page of LocalInstance records from the API. + Request is executed immediately - @property - def voice_fallback_method(self): - """ - :returns: The voice_fallback_method - :rtype: unicode - """ - return self._properties['voice_fallback_method'] + :param target_url: API-generated URL for the requested results page - @property - def voice_fallback_url(self): - """ - :returns: The voice_fallback_url - :rtype: unicode + :returns: Page of LocalInstance """ - return self._properties['voice_fallback_url'] + response = self._version.domain.twilio.request("GET", target_url) + return LocalPage(self._version, response, self._solution) - @property - def voice_method(self): + async def get_page_async(self, target_url: str) -> LocalPage: """ - :returns: The voice_method - :rtype: unicode - """ - return self._properties['voice_method'] + Asynchronously retrieve a specific page of LocalInstance records from the API. + Request is executed immediately - @property - def voice_url(self): - """ - :returns: The voice_url - :rtype: unicode + :param target_url: API-generated URL for the requested results page + + :returns: Page of LocalInstance """ - return self._properties['voice_url'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return LocalPage(self._version, response, self._solution) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/api/v2010/account/incoming_phone_number/mobile.py b/twilio/rest/api/v2010/account/incoming_phone_number/mobile.py index 54c4d77a0f..27fc8a0e9f 100644 --- a/twilio/rest/api/v2010/account/incoming_phone_number/mobile.py +++ b/twilio/rest/api/v2010/account/incoming_phone_number/mobile.py @@ -1,554 +1,676 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 MobileList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the MobileList - - :param Version version: Version that contains the resource - :param account_sid: The unique sid that identifies this account - - :returns: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileList - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileList - """ - super(MobileList, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/IncomingPhoneNumbers/Mobile.json'.format(**self._solution) - - def stream(self, beta=values.unset, friendly_name=values.unset, - phone_number=values.unset, origin=values.unset, limit=None, - page_size=None): - """ - 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: The beta - :param unicode friendly_name: The friendly_name - :param unicode phone_number: The phone_number - :param unicode origin: The origin - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) +class MobileInstance(InstanceResource): - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileInstance] - """ - limits = self._version.read_limits(limit, page_size) + class AddressRequirement(object): + NONE = "none" + ANY = "any" + LOCAL = "local" + FOREIGN = "foreign" - page = self.page( - beta=beta, - friendly_name=friendly_name, - phone_number=phone_number, - origin=origin, - page_size=limits['page_size'], + 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, + } - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, beta=values.unset, friendly_name=values.unset, - phone_number=values.unset, origin=values.unset, limit=None, - page_size=None): - """ - 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: The beta - :param unicode friendly_name: The friendly_name - :param unicode phone_number: The phone_number - :param unicode origin: The origin - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileInstance] + def __repr__(self) -> str: """ - return list(self.stream( - beta=beta, - friendly_name=friendly_name, - phone_number=phone_number, - origin=origin, - limit=limit, - page_size=page_size, - )) - - def page(self, beta=values.unset, friendly_name=values.unset, - phone_number=values.unset, origin=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of MobileInstance records from the API. - Request is executed immediately - - :param bool beta: The beta - :param unicode friendly_name: The friendly_name - :param unicode phone_number: The phone_number - :param unicode origin: The origin - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + Provide a friendly representation - :returns: Page of MobileInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobilePage + :returns: Machine friendly representation """ - params = values.of({ - 'Beta': beta, - 'FriendlyName': friendly_name, - 'PhoneNumber': phone_number, - 'Origin': origin, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - return MobilePage(self._version, response, self._solution) +class MobilePage(Page): - def get_page(self, target_url): + def get_instance(self, payload: Dict[str, Any]) -> MobileInstance: """ - Retrieve a specific page of MobileInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page + Build an instance of MobileInstance - :returns: Page of MobileInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobilePage + :param payload: Payload response from the API """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return MobileInstance( + self._version, payload, account_sid=self._solution["account_sid"] ) - return MobilePage(self._version, response, self._solution) - - def create(self, phone_number, api_version=values.unset, - friendly_name=values.unset, sms_application_sid=values.unset, - sms_fallback_method=values.unset, sms_fallback_url=values.unset, - sms_method=values.unset, sms_url=values.unset, - status_callback=values.unset, status_callback_method=values.unset, - voice_application_sid=values.unset, - voice_caller_id_lookup=values.unset, - voice_fallback_method=values.unset, voice_fallback_url=values.unset, - voice_method=values.unset, voice_url=values.unset, - identity_sid=values.unset, address_sid=values.unset): - """ - Create a new MobileInstance - - :param unicode phone_number: The phone_number - :param unicode api_version: The api_version - :param unicode friendly_name: The friendly_name - :param unicode sms_application_sid: The sms_application_sid - :param unicode sms_fallback_method: The sms_fallback_method - :param unicode sms_fallback_url: The sms_fallback_url - :param unicode sms_method: The sms_method - :param unicode sms_url: The sms_url - :param unicode status_callback: The status_callback - :param unicode status_callback_method: The status_callback_method - :param unicode voice_application_sid: The voice_application_sid - :param bool voice_caller_id_lookup: The voice_caller_id_lookup - :param unicode voice_fallback_method: The voice_fallback_method - :param unicode voice_fallback_url: The voice_fallback_url - :param unicode voice_method: The voice_method - :param unicode voice_url: The voice_url - :param unicode identity_sid: The identity_sid - :param unicode address_sid: The address_sid - - :returns: Newly created MobileInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.mobile.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': voice_caller_id_lookup, - 'VoiceFallbackMethod': voice_fallback_method, - 'VoiceFallbackUrl': voice_fallback_url, - 'VoiceMethod': voice_method, - 'VoiceUrl': voice_url, - 'IdentitySid': identity_sid, - 'AddressSid': address_sid, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return MobileInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class MobilePage(Page): - """ """ +class MobileList(ListResource): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str): """ - Initialize the MobilePage + Initialize the MobileList - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The unique sid that identifies this account + :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. - :returns: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobilePage - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobilePage """ - super(MobilePage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/Mobile.json".format( + **self._solution + ) - def get_instance(self, payload): - """ - Build an instance of MobileInstance + 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"}) - :param dict payload: Payload response from the API + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileInstance - """ - return MobileInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + headers["Accept"] = "application/json" - def __repr__(self): - """ - Provide a friendly representation + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: Machine friendly representation - :rtype: str - """ - return '' + 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"}) -class MobileInstance(InstanceResource): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - class AddressRequirement(object): - NONE = "none" - ANY = "any" - LOCAL = "local" - FOREIGN = "foreign" + headers["Accept"] = "application/json" - def __init__(self, version, payload, account_sid): - """ - Initialize the MobileInstance - - :returns: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileInstance - """ - super(MobileInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'address_sid': payload['address_sid'], - 'address_requirements': payload['address_requirements'], - 'api_version': payload['api_version'], - 'beta': payload['beta'], - 'capabilities': payload['capabilities'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'friendly_name': payload['friendly_name'], - 'identity_sid': payload['identity_sid'], - 'phone_number': payload['phone_number'], - 'origin': payload['origin'], - 'sid': payload['sid'], - 'sms_application_sid': payload['sms_application_sid'], - 'sms_fallback_method': payload['sms_fallback_method'], - 'sms_fallback_url': payload['sms_fallback_url'], - 'sms_method': payload['sms_method'], - 'sms_url': payload['sms_url'], - 'status_callback': payload['status_callback'], - 'status_callback_method': payload['status_callback_method'], - 'trunk_sid': payload['trunk_sid'], - 'uri': payload['uri'], - 'voice_application_sid': payload['voice_application_sid'], - 'voice_caller_id_lookup': payload['voice_caller_id_lookup'], - 'voice_fallback_method': payload['voice_fallback_method'], - 'voice_fallback_url': payload['voice_fallback_url'], - 'voice_method': payload['voice_method'], - 'voice_url': payload['voice_url'], - } + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + return MobileInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + 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]: """ - return self._properties['account_sid'] + 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. - @property - def address_sid(self): - """ - :returns: The address_sid - :rtype: unicode - """ - return self._properties['address_sid'] + :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) - @property - def address_requirements(self): - """ - :returns: The address_requirements - :rtype: MobileInstance.AddressRequirement + :returns: Generator that will yield up to limit results """ - return self._properties['address_requirements'] + 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"], + ) - @property - def api_version(self): - """ - :returns: The api_version - :rtype: unicode - """ - return self._properties['api_version'] + return self._version.stream(page, limits["limit"]) - @property - def beta(self): - """ - :returns: The beta - :rtype: bool + 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]: """ - return self._properties['beta'] + 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. - @property - def capabilities(self): - """ - :returns: The capabilities - :rtype: unicode - """ - return self._properties['capabilities'] + :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) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime + :returns: Generator that will yield up to limit results """ - return self._properties['date_created'] + 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"], + ) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + return self._version.stream_async(page, limits["limit"]) - @property - def friendly_name(self): + 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]: """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] + Lists MobileInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def identity_sid(self): - """ - :returns: The identity_sid - :rtype: unicode - """ - return self._properties['identity_sid'] + :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, + ) + ) - @property - def phone_number(self): - """ - :returns: The phone_number - :rtype: unicode - """ - return self._properties['phone_number'] + 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. - @property - def origin(self): + :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: """ - :returns: The origin - :rtype: unicode - """ - return self._properties['origin'] + Retrieve a single page of MobileInstance records from the API. + Request is executed immediately - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + :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 - @property - def sms_application_sid(self): - """ - :returns: The sms_application_sid - :rtype: unicode + :returns: Page of MobileInstance """ - return self._properties['sms_application_sid'] + 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, + } + ) - @property - def sms_fallback_method(self): - """ - :returns: The sms_fallback_method - :rtype: unicode - """ - return self._properties['sms_fallback_method'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def sms_fallback_url(self): - """ - :returns: The sms_fallback_url - :rtype: unicode - """ - return self._properties['sms_fallback_url'] + headers["Accept"] = "application/json" - @property - def sms_method(self): - """ - :returns: The sms_method - :rtype: unicode - """ - return self._properties['sms_method'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MobilePage(self._version, response, self._solution) - @property - def sms_url(self): - """ - :returns: The sms_url - :rtype: unicode - """ - return self._properties['sms_url'] + 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 - @property - def status_callback(self): - """ - :returns: The status_callback - :rtype: unicode - """ - return self._properties['status_callback'] + :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 - @property - def status_callback_method(self): - """ - :returns: The status_callback_method - :rtype: unicode + :returns: Page of MobileInstance """ - return self._properties['status_callback_method'] + 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, + } + ) - @property - def trunk_sid(self): - """ - :returns: The trunk_sid - :rtype: unicode - """ - return self._properties['trunk_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def uri(self): - """ - :returns: The uri - :rtype: unicode - """ - return self._properties['uri'] + headers["Accept"] = "application/json" - @property - def voice_application_sid(self): - """ - :returns: The voice_application_sid - :rtype: unicode - """ - return self._properties['voice_application_sid'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MobilePage(self._version, response, self._solution) - @property - def voice_caller_id_lookup(self): - """ - :returns: The voice_caller_id_lookup - :rtype: bool + def get_page(self, target_url: str) -> MobilePage: """ - return self._properties['voice_caller_id_lookup'] + Retrieve a specific page of MobileInstance records from the API. + Request is executed immediately - @property - def voice_fallback_method(self): - """ - :returns: The voice_fallback_method - :rtype: unicode - """ - return self._properties['voice_fallback_method'] + :param target_url: API-generated URL for the requested results page - @property - def voice_fallback_url(self): - """ - :returns: The voice_fallback_url - :rtype: unicode + :returns: Page of MobileInstance """ - return self._properties['voice_fallback_url'] + response = self._version.domain.twilio.request("GET", target_url) + return MobilePage(self._version, response, self._solution) - @property - def voice_method(self): + async def get_page_async(self, target_url: str) -> MobilePage: """ - :returns: The voice_method - :rtype: unicode - """ - return self._properties['voice_method'] + Asynchronously retrieve a specific page of MobileInstance records from the API. + Request is executed immediately - @property - def voice_url(self): - """ - :returns: The voice_url - :rtype: unicode + :param target_url: API-generated URL for the requested results page + + :returns: Page of MobileInstance """ - return self._properties['voice_url'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return MobilePage(self._version, response, self._solution) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" 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 index 1023cce510..86290ff9b2 100644 --- a/twilio/rest/api/v2010/account/incoming_phone_number/toll_free.py +++ b/twilio/rest/api/v2010/account/incoming_phone_number/toll_free.py @@ -1,554 +1,676 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 TollFreeList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the TollFreeList - - :param Version version: Version that contains the resource - :param account_sid: The unique sid that identifies this account - - :returns: twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreeList - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreeList - """ - super(TollFreeList, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/IncomingPhoneNumbers/TollFree.json'.format(**self._solution) - - def stream(self, beta=values.unset, friendly_name=values.unset, - phone_number=values.unset, origin=values.unset, limit=None, - page_size=None): - """ - 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: The beta - :param unicode friendly_name: The friendly_name - :param unicode phone_number: The phone_number - :param unicode origin: The origin - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) +class TollFreeInstance(InstanceResource): - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreeInstance] - """ - limits = self._version.read_limits(limit, page_size) + class AddressRequirement(object): + NONE = "none" + ANY = "any" + LOCAL = "local" + FOREIGN = "foreign" - page = self.page( - beta=beta, - friendly_name=friendly_name, - phone_number=phone_number, - origin=origin, - page_size=limits['page_size'], + 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, + } - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, beta=values.unset, friendly_name=values.unset, - phone_number=values.unset, origin=values.unset, limit=None, - page_size=None): - """ - 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: The beta - :param unicode friendly_name: The friendly_name - :param unicode phone_number: The phone_number - :param unicode origin: The origin - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreeInstance] + def __repr__(self) -> str: """ - return list(self.stream( - beta=beta, - friendly_name=friendly_name, - phone_number=phone_number, - origin=origin, - limit=limit, - page_size=page_size, - )) - - def page(self, beta=values.unset, friendly_name=values.unset, - phone_number=values.unset, origin=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of TollFreeInstance records from the API. - Request is executed immediately - - :param bool beta: The beta - :param unicode friendly_name: The friendly_name - :param unicode phone_number: The phone_number - :param unicode origin: The origin - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + Provide a friendly representation - :returns: Page of TollFreeInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreePage + :returns: Machine friendly representation """ - params = values.of({ - 'Beta': beta, - 'FriendlyName': friendly_name, - 'PhoneNumber': phone_number, - 'Origin': origin, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - return TollFreePage(self._version, response, self._solution) +class TollFreePage(Page): - def get_page(self, target_url): + def get_instance(self, payload: Dict[str, Any]) -> TollFreeInstance: """ - Retrieve a specific page of TollFreeInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page + Build an instance of TollFreeInstance - :returns: Page of TollFreeInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreePage + :param payload: Payload response from the API """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return TollFreeInstance( + self._version, payload, account_sid=self._solution["account_sid"] ) - return TollFreePage(self._version, response, self._solution) - - def create(self, phone_number, api_version=values.unset, - friendly_name=values.unset, sms_application_sid=values.unset, - sms_fallback_method=values.unset, sms_fallback_url=values.unset, - sms_method=values.unset, sms_url=values.unset, - status_callback=values.unset, status_callback_method=values.unset, - voice_application_sid=values.unset, - voice_caller_id_lookup=values.unset, - voice_fallback_method=values.unset, voice_fallback_url=values.unset, - voice_method=values.unset, voice_url=values.unset, - identity_sid=values.unset, address_sid=values.unset): - """ - Create a new TollFreeInstance - - :param unicode phone_number: The phone_number - :param unicode api_version: The api_version - :param unicode friendly_name: The friendly_name - :param unicode sms_application_sid: The sms_application_sid - :param unicode sms_fallback_method: The sms_fallback_method - :param unicode sms_fallback_url: The sms_fallback_url - :param unicode sms_method: The sms_method - :param unicode sms_url: The sms_url - :param unicode status_callback: The status_callback - :param unicode status_callback_method: The status_callback_method - :param unicode voice_application_sid: The voice_application_sid - :param bool voice_caller_id_lookup: The voice_caller_id_lookup - :param unicode voice_fallback_method: The voice_fallback_method - :param unicode voice_fallback_url: The voice_fallback_url - :param unicode voice_method: The voice_method - :param unicode voice_url: The voice_url - :param unicode identity_sid: The identity_sid - :param unicode address_sid: The address_sid - - :returns: Newly created TollFreeInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.toll_free.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': voice_caller_id_lookup, - 'VoiceFallbackMethod': voice_fallback_method, - 'VoiceFallbackUrl': voice_fallback_url, - 'VoiceMethod': voice_method, - 'VoiceUrl': voice_url, - 'IdentitySid': identity_sid, - 'AddressSid': address_sid, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return TollFreeInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class TollFreePage(Page): - """ """ +class TollFreeList(ListResource): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str): """ - Initialize the TollFreePage + Initialize the TollFreeList - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The unique sid that identifies this account + :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. - :returns: twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreePage - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreePage """ - super(TollFreePage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/TollFree.json".format( + **self._solution + ) - def get_instance(self, payload): - """ - Build an instance of TollFreeInstance + 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"}) - :param dict payload: Payload response from the API + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreeInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreeInstance - """ - return TollFreeInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + headers["Accept"] = "application/json" - def __repr__(self): - """ - Provide a friendly representation + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: Machine friendly representation - :rtype: str - """ - return '' + 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"}) -class TollFreeInstance(InstanceResource): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - class AddressRequirement(object): - NONE = "none" - ANY = "any" - LOCAL = "local" - FOREIGN = "foreign" + headers["Accept"] = "application/json" - def __init__(self, version, payload, account_sid): - """ - Initialize the TollFreeInstance - - :returns: twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreeInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreeInstance - """ - super(TollFreeInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'address_sid': payload['address_sid'], - 'address_requirements': payload['address_requirements'], - 'api_version': payload['api_version'], - 'beta': payload['beta'], - 'capabilities': payload['capabilities'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'friendly_name': payload['friendly_name'], - 'identity_sid': payload['identity_sid'], - 'phone_number': payload['phone_number'], - 'origin': payload['origin'], - 'sid': payload['sid'], - 'sms_application_sid': payload['sms_application_sid'], - 'sms_fallback_method': payload['sms_fallback_method'], - 'sms_fallback_url': payload['sms_fallback_url'], - 'sms_method': payload['sms_method'], - 'sms_url': payload['sms_url'], - 'status_callback': payload['status_callback'], - 'status_callback_method': payload['status_callback_method'], - 'trunk_sid': payload['trunk_sid'], - 'uri': payload['uri'], - 'voice_application_sid': payload['voice_application_sid'], - 'voice_caller_id_lookup': payload['voice_caller_id_lookup'], - 'voice_fallback_method': payload['voice_fallback_method'], - 'voice_fallback_url': payload['voice_fallback_url'], - 'voice_method': payload['voice_method'], - 'voice_url': payload['voice_url'], - } + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + return TollFreeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + 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]: """ - return self._properties['account_sid'] + 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. - @property - def address_sid(self): - """ - :returns: The address_sid - :rtype: unicode - """ - return self._properties['address_sid'] + :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) - @property - def address_requirements(self): - """ - :returns: The address_requirements - :rtype: TollFreeInstance.AddressRequirement + :returns: Generator that will yield up to limit results """ - return self._properties['address_requirements'] + 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"], + ) - @property - def api_version(self): - """ - :returns: The api_version - :rtype: unicode - """ - return self._properties['api_version'] + return self._version.stream(page, limits["limit"]) - @property - def beta(self): - """ - :returns: The beta - :rtype: bool + 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]: """ - return self._properties['beta'] + 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. - @property - def capabilities(self): - """ - :returns: The capabilities - :rtype: unicode - """ - return self._properties['capabilities'] + :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) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime + :returns: Generator that will yield up to limit results """ - return self._properties['date_created'] + 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"], + ) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + return self._version.stream_async(page, limits["limit"]) - @property - def friendly_name(self): + 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]: """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] + Lists TollFreeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def identity_sid(self): - """ - :returns: The identity_sid - :rtype: unicode - """ - return self._properties['identity_sid'] + :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, + ) + ) - @property - def phone_number(self): - """ - :returns: The phone_number - :rtype: unicode - """ - return self._properties['phone_number'] + 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. - @property - def origin(self): + :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: """ - :returns: The origin - :rtype: unicode - """ - return self._properties['origin'] + Retrieve a single page of TollFreeInstance records from the API. + Request is executed immediately - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + :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 - @property - def sms_application_sid(self): - """ - :returns: The sms_application_sid - :rtype: unicode + :returns: Page of TollFreeInstance """ - return self._properties['sms_application_sid'] + 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, + } + ) - @property - def sms_fallback_method(self): - """ - :returns: The sms_fallback_method - :rtype: unicode - """ - return self._properties['sms_fallback_method'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def sms_fallback_url(self): - """ - :returns: The sms_fallback_url - :rtype: unicode - """ - return self._properties['sms_fallback_url'] + headers["Accept"] = "application/json" - @property - def sms_method(self): - """ - :returns: The sms_method - :rtype: unicode - """ - return self._properties['sms_method'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TollFreePage(self._version, response, self._solution) - @property - def sms_url(self): - """ - :returns: The sms_url - :rtype: unicode - """ - return self._properties['sms_url'] + 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 - @property - def status_callback(self): - """ - :returns: The status_callback - :rtype: unicode - """ - return self._properties['status_callback'] + :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 - @property - def status_callback_method(self): - """ - :returns: The status_callback_method - :rtype: unicode + :returns: Page of TollFreeInstance """ - return self._properties['status_callback_method'] + 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, + } + ) - @property - def trunk_sid(self): - """ - :returns: The trunk_sid - :rtype: unicode - """ - return self._properties['trunk_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def uri(self): - """ - :returns: The uri - :rtype: unicode - """ - return self._properties['uri'] + headers["Accept"] = "application/json" - @property - def voice_application_sid(self): - """ - :returns: The voice_application_sid - :rtype: unicode - """ - return self._properties['voice_application_sid'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TollFreePage(self._version, response, self._solution) - @property - def voice_caller_id_lookup(self): - """ - :returns: The voice_caller_id_lookup - :rtype: bool + def get_page(self, target_url: str) -> TollFreePage: """ - return self._properties['voice_caller_id_lookup'] + Retrieve a specific page of TollFreeInstance records from the API. + Request is executed immediately - @property - def voice_fallback_method(self): - """ - :returns: The voice_fallback_method - :rtype: unicode - """ - return self._properties['voice_fallback_method'] + :param target_url: API-generated URL for the requested results page - @property - def voice_fallback_url(self): - """ - :returns: The voice_fallback_url - :rtype: unicode + :returns: Page of TollFreeInstance """ - return self._properties['voice_fallback_url'] + response = self._version.domain.twilio.request("GET", target_url) + return TollFreePage(self._version, response, self._solution) - @property - def voice_method(self): + async def get_page_async(self, target_url: str) -> TollFreePage: """ - :returns: The voice_method - :rtype: unicode - """ - return self._properties['voice_method'] + Asynchronously retrieve a specific page of TollFreeInstance records from the API. + Request is executed immediately - @property - def voice_url(self): - """ - :returns: The voice_url - :rtype: unicode + :param target_url: API-generated URL for the requested results page + + :returns: Page of TollFreeInstance """ - return self._properties['voice_url'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return TollFreePage(self._version, response, self._solution) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/api/v2010/account/key.py b/twilio/rest/api/v2010/account/key.py index 3089eae3a4..8b18dbd4ba 100644 --- a/twilio/rest/api/v2010/account/key.py +++ b/twilio/rest/api/v2010/account/key.py @@ -1,385 +1,566 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 KeyList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the KeyList +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") + ) - :param Version version: Version that contains the resource - :param account_sid: A 34 character string that uniquely identifies this resource. + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[KeyContext] = None - :returns: twilio.rest.api.v2010.account.key.KeyList - :rtype: twilio.rest.api.v2010.account.key.KeyList + @property + def _proxy(self) -> "KeyContext": """ - super(KeyList, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Keys.json'.format(**self._solution) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def stream(self, limit=None, page_size=None): + :returns: KeyContext for this 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + if self._context is None: + self._context = KeyContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.key.KeyInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the KeyInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists KeyInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the KeyInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.key.KeyInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "KeyInstance": """ - Retrieve a single page of KeyInstance records from the API. - Request is executed immediately + Fetch the KeyInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of KeyInstance - :rtype: twilio.rest.api.v2010.account.key.KeyPage + :returns: The fetched KeyInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return KeyPage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "KeyInstance": """ - Retrieve a specific page of KeyInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the KeyInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of KeyInstance - :rtype: twilio.rest.api.v2010.account.key.KeyPage + :returns: The fetched KeyInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return KeyPage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def get(self, sid): + def update(self, friendly_name: Union[str, object] = values.unset) -> "KeyInstance": """ - Constructs a KeyContext + Update the KeyInstance - :param sid: The sid + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: twilio.rest.api.v2010.account.key.KeyContext - :rtype: twilio.rest.api.v2010.account.key.KeyContext + :returns: The updated KeyInstance """ - return KeyContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.update( + friendly_name=friendly_name, + ) - def __call__(self, sid): + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "KeyInstance": """ - Constructs a KeyContext + Asynchronous coroutine to update the KeyInstance - :param sid: The sid + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: twilio.rest.api.v2010.account.key.KeyContext - :rtype: twilio.rest.api.v2010.account.key.KeyContext + :returns: The updated KeyInstance """ - return KeyContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return await self._proxy.update_async( + friendly_name=friendly_name, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class KeyPage(Page): - """ """ +class KeyContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str, sid: str): """ - Initialize the KeyPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: A 34 character string that uniquely identifies this resource. + Initialize the KeyContext - :returns: twilio.rest.api.v2010.account.key.KeyPage - :rtype: twilio.rest.api.v2010.account.key.KeyPage + :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(KeyPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Keys/{sid}.json".format(**self._solution) - def get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of KeyInstance + Deletes the KeyInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.api.v2010.account.key.KeyInstance - :rtype: twilio.rest.api.v2010.account.key.KeyInstance + :returns: True if delete succeeds, False otherwise """ - return KeyInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the KeyInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class KeyContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, account_sid, sid): + def fetch(self) -> KeyInstance: """ - Initialize the KeyContext + Fetch the KeyInstance - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param sid: The sid - :returns: twilio.rest.api.v2010.account.key.KeyContext - :rtype: twilio.rest.api.v2010.account.key.KeyContext + :returns: The fetched KeyInstance """ - super(KeyContext, self).__init__(version) - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/Keys/{sid}.json'.format(**self._solution) + 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"], + ) - def fetch(self): + async def fetch_async(self) -> KeyInstance: """ - Fetch a KeyInstance + Asynchronous coroutine to fetch the KeyInstance - :returns: Fetched KeyInstance - :rtype: twilio.rest.api.v2010.account.key.KeyInstance + + :returns: The fetched KeyInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def update(self, friendly_name=values.unset): + def update(self, friendly_name: Union[str, object] = values.unset) -> KeyInstance: """ Update the KeyInstance - :param unicode friendly_name: The friendly_name + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: Updated KeyInstance - :rtype: twilio.rest.api.v2010.account.key.KeyInstance + :returns: The updated KeyInstance """ - data = values.of({'FriendlyName': friendly_name, }) + + 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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) return KeyInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> KeyInstance: """ - Deletes the KeyInstance + Asynchronous coroutine to update the KeyInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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._version.delete('delete', self._uri) - def __repr__(self): + 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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class KeyInstance(InstanceResource): - """ """ +class KeyPage(Page): - def __init__(self, version, payload, account_sid, sid=None): + def get_instance(self, payload: Dict[str, Any]) -> KeyInstance: """ - Initialize the KeyInstance + Build an instance of KeyInstance - :returns: twilio.rest.api.v2010.account.key.KeyInstance - :rtype: twilio.rest.api.v2010.account.key.KeyInstance + :param payload: Payload response from the API """ - super(KeyInstance, self).__init__(version) + return KeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +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) - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'friendly_name': payload['friendly_name'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), + # Path Solution + self._solution = { + "account_sid": account_sid, } + self._uri = "/Accounts/{account_sid}/Keys.json".format(**self._solution) - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } + 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. - @property - def _proxy(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - :returns: KeyContext for this KeyInstance - :rtype: twilio.rest.api.v2010.account.key.KeyContext + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[KeyInstance]: """ - if self._context is None: - self._context = KeyContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + 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. - @property - def sid(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The sid - :rtype: unicode + 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]: """ - return self._properties['sid'] + Lists KeyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def friendly_name(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The friendly_name - :rtype: unicode + 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]: """ - return self._properties['friendly_name'] + 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. - @property - def date_created(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The date_created - :rtype: datetime + 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: """ - return self._properties['date_created'] + Retrieve a single page of KeyInstance records from the API. + Request is executed immediately - @property - def date_updated(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The date_updated - :rtype: datetime + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page of KeyInstance records from the API. + Request is executed immediately - def fetch(self): + :param page_token: PageToken provided by the API + :param page_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 """ - Fetch a KeyInstance + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: Fetched KeyInstance - :rtype: twilio.rest.api.v2010.account.key.KeyInstance + headers = values.of({"Content-Type": "application/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: """ - return self._proxy.fetch() + 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 - def update(self, friendly_name=values.unset): + :returns: Page of KeyInstance """ - Update the 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 unicode friendly_name: The friendly_name + :param target_url: API-generated URL for the requested results page - :returns: Updated KeyInstance - :rtype: twilio.rest.api.v2010.account.key.KeyInstance + :returns: Page of KeyInstance """ - return self._proxy.update(friendly_name=friendly_name, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return KeyPage(self._version, response, self._solution) - def delete(self): + def get(self, sid: str) -> KeyContext: """ - Deletes the KeyInstance + Constructs a KeyContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the Key resource to update. """ - return self._proxy.delete() + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/api/v2010/account/message/__init__.py b/twilio/rest/api/v2010/account/message/__init__.py index cb651edd41..d5369d11ce 100644 --- a/twilio/rest/api/v2010/account/message/__init__.py +++ b/twilio/rest/api/v2010/account/message/__init__.py @@ -1,716 +1,1014 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 MessageList(ListResource): - """ """ +class MessageInstance(InstanceResource): - def __init__(self, version, account_sid): - """ - Initialize the MessageList + class AddressRetention(object): + RETAIN = "retain" + OBFUSCATE = "obfuscate" - :param Version version: Version that contains the resource - :param account_sid: The unique sid that identifies this account + class ContentRetention(object): + RETAIN = "retain" + DISCARD = "discard" - :returns: twilio.rest.api.v2010.account.message.MessageList - :rtype: twilio.rest.api.v2010.account.message.MessageList - """ - super(MessageList, self).__init__(version) + class Direction(object): + INBOUND = "inbound" + OUTBOUND_API = "outbound-api" + OUTBOUND_CALL = "outbound-call" + OUTBOUND_REPLY = "outbound-reply" - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Messages.json'.format(**self._solution) - - def create(self, to, status_callback=values.unset, application_sid=values.unset, - max_price=values.unset, provide_feedback=values.unset, - validity_period=values.unset, max_rate=values.unset, - force_delivery=values.unset, provider_sid=values.unset, - content_retention=values.unset, address_retention=values.unset, - smart_encoded=values.unset, from_=values.unset, - messaging_service_sid=values.unset, body=values.unset, - media_url=values.unset): - """ - Create a new MessageInstance - - :param unicode to: The phone number to receive the message - :param unicode status_callback: URL Twilio will request when the status changes - :param unicode application_sid: The application to use for callbacks - :param unicode max_price: The max_price - :param bool provide_feedback: The provide_feedback - :param unicode validity_period: The validity_period - :param unicode max_rate: The max_rate - :param bool force_delivery: The force_delivery - :param unicode provider_sid: The provider_sid - :param MessageInstance.ContentRetention content_retention: The content_retention - :param MessageInstance.AddressRetention address_retention: The address_retention - :param bool smart_encoded: The smart_encoded - :param unicode from_: The phone number that initiated the message - :param unicode messaging_service_sid: The messaging_service_sid - :param unicode body: The body - :param unicode media_url: The media_url - - :returns: Newly created MessageInstance - :rtype: twilio.rest.api.v2010.account.message.MessageInstance - """ - data = values.of({ - 'To': to, - 'From': from_, - 'MessagingServiceSid': messaging_service_sid, - 'Body': body, - 'MediaUrl': serialize.map(media_url, lambda e: e), - 'StatusCallback': status_callback, - 'ApplicationSid': application_sid, - 'MaxPrice': max_price, - 'ProvideFeedback': provide_feedback, - 'ValidityPeriod': validity_period, - 'MaxRate': max_rate, - 'ForceDelivery': force_delivery, - 'ProviderSid': provider_sid, - 'ContentRetention': content_retention, - 'AddressRetention': address_retention, - 'SmartEncoded': smart_encoded, - }) + class RiskCheck(object): + ENABLE = "enable" + DISABLE = "disable" - payload = self._version.create( - 'POST', - self._uri, - data=data, + 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" ) - return MessageInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[MessageContext] = None - def stream(self, to=values.unset, from_=values.unset, - date_sent_before=values.unset, date_sent=values.unset, - date_sent_after=values.unset, limit=None, page_size=None): + @property + def _proxy(self) -> "MessageContext": """ - 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. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param unicode to: Filter by messages to this number - :param unicode from_: Filter by from number - :param datetime date_sent_before: Filter by date sent - :param datetime date_sent: Filter by date sent - :param datetime date_sent_after: Filter by date sent - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.message.MessageInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the MessageInstance - page = self.page( - to=to, - from_=from_, - date_sent_before=date_sent_before, - date_sent=date_sent, - date_sent_after=date_sent_after, - page_size=limits['page_size'], - ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, to=values.unset, from_=values.unset, - date_sent_before=values.unset, date_sent=values.unset, - date_sent_after=values.unset, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists MessageInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the MessageInstance - :param unicode to: Filter by messages to this number - :param unicode from_: Filter by from number - :param datetime date_sent_before: Filter by date sent - :param datetime date_sent: Filter by date sent - :param datetime date_sent_after: Filter by date sent - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.message.MessageInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream( - to=to, - from_=from_, - date_sent_before=date_sent_before, - date_sent=date_sent, - date_sent_after=date_sent_after, - limit=limit, - page_size=page_size, - )) + return await self._proxy.delete_async() - def page(self, to=values.unset, from_=values.unset, - date_sent_before=values.unset, date_sent=values.unset, - date_sent_after=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch(self) -> "MessageInstance": """ - Retrieve a single page of MessageInstance records from the API. - Request is executed immediately + Fetch the MessageInstance - :param unicode to: Filter by messages to this number - :param unicode from_: Filter by from number - :param datetime date_sent_before: Filter by date sent - :param datetime date_sent: Filter by date sent - :param datetime date_sent_after: Filter by date sent - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of MessageInstance - :rtype: twilio.rest.api.v2010.account.message.MessagePage - """ - params = values.of({ - 'To': to, - 'From': from_, - 'DateSent<': serialize.iso8601_datetime(date_sent_before), - 'DateSent': serialize.iso8601_datetime(date_sent), - 'DateSent>': serialize.iso8601_datetime(date_sent_after), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + :returns: The fetched MessageInstance + """ + return self._proxy.fetch() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + async def fetch_async(self) -> "MessageInstance": + """ + Asynchronous coroutine to fetch the MessageInstance - return MessagePage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched MessageInstance """ - Retrieve a specific page of MessageInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_async() - :param str target_url: API-generated URL for the requested results page + def update( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> "MessageInstance": + """ + Update the MessageInstance - :returns: Page of MessageInstance - :rtype: twilio.rest.api.v2010.account.message.MessagePage + :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 """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + body=body, + status=status, ) - return MessagePage(self._version, response, self._solution) - - def get(self, sid): + async def update_async( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> "MessageInstance": """ - Constructs a MessageContext + Asynchronous coroutine to update the MessageInstance - :param sid: Fetch by unique message Sid + :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: twilio.rest.api.v2010.account.message.MessageContext - :rtype: twilio.rest.api.v2010.account.message.MessageContext + :returns: The updated MessageInstance """ - return MessageContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return await self._proxy.update_async( + body=body, + status=status, + ) - def __call__(self, sid): + @property + def feedback(self) -> FeedbackList: """ - Constructs a MessageContext - - :param sid: Fetch by unique message Sid + Access the feedback + """ + return self._proxy.feedback - :returns: twilio.rest.api.v2010.account.message.MessageContext - :rtype: twilio.rest.api.v2010.account.message.MessageContext + @property + def media(self) -> MediaList: + """ + Access the media """ - return MessageContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.media - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class MessagePage(Page): - """ """ +class MessageContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str, sid: str): """ - Initialize the MessagePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The unique sid that identifies this account + Initialize the MessageContext - :returns: twilio.rest.api.v2010.account.message.MessagePage - :rtype: twilio.rest.api.v2010.account.message.MessagePage + :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(MessagePage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of MessageInstance + Deletes the MessageInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.api.v2010.account.message.MessageInstance - :rtype: twilio.rest.api.v2010.account.message.MessageInstance + :returns: True if delete succeeds, False otherwise """ - return MessageInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the MessageInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class MessageContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, account_sid, sid): + def fetch(self) -> MessageInstance: """ - Initialize the MessageContext + Fetch the MessageInstance - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param sid: Fetch by unique message Sid - :returns: twilio.rest.api.v2010.account.message.MessageContext - :rtype: twilio.rest.api.v2010.account.message.MessageContext + :returns: The fetched MessageInstance """ - super(MessageContext, self).__init__(version) - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/Messages/{sid}.json'.format(**self._solution) + headers = values.of({}) - # Dependents - self._media = None - self._feedback = None + headers["Accept"] = "application/json" - def delete(self): - """ - Deletes the MessageInstance + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + return MessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - def fetch(self): + async def fetch_async(self) -> MessageInstance: """ - Fetch a MessageInstance + Asynchronous coroutine to fetch the MessageInstance + - :returns: Fetched MessageInstance - :rtype: twilio.rest.api.v2010.account.message.MessageInstance + :returns: The fetched MessageInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def update(self, body): + def update( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> MessageInstance: """ Update the MessageInstance - :param unicode body: The body + :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: Updated MessageInstance - :rtype: twilio.rest.api.v2010.account.message.MessageInstance + :returns: The updated MessageInstance """ - data = values.of({'Body': body, }) + + 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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) return MessageInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - @property - def media(self): + async def update_async( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> MessageInstance: """ - Access the media + Asynchronous coroutine to update the MessageInstance - :returns: twilio.rest.api.v2010.account.message.media.MediaList - :rtype: twilio.rest.api.v2010.account.message.media.MediaList + :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 """ - if self._media is None: - self._media = MediaList( - self._version, - account_sid=self._solution['account_sid'], - message_sid=self._solution['sid'], - ) - return self._media + + 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): + def feedback(self) -> FeedbackList: """ Access the feedback - - :returns: twilio.rest.api.v2010.account.message.feedback.FeedbackList - :rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackList """ if self._feedback is None: self._feedback = FeedbackList( self._version, - account_sid=self._solution['account_sid'], - message_sid=self._solution['sid'], + self._solution["account_sid"], + self._solution["sid"], ) return self._feedback - def __repr__(self): + @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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class MessageInstance(InstanceResource): - """ """ +class MessagePage(Page): - class Status(object): - QUEUED = "queued" - SENDING = "sending" - SENT = "sent" - FAILED = "failed" - DELIVERED = "delivered" - UNDELIVERED = "undelivered" - RECEIVING = "receiving" - RECEIVED = "received" - ACCEPTED = "accepted" + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: + """ + Build an instance of MessageInstance - class Direction(object): - INBOUND = "inbound" - OUTBOUND_API = "outbound-api" - OUTBOUND_CALL = "outbound-call" - OUTBOUND_REPLY = "outbound-reply" + :param payload: Payload response from the API + """ + return MessageInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - class ContentRetention(object): - RETAIN = "retain" - DISCARD = "discard" + def __repr__(self) -> str: + """ + Provide a friendly representation - class AddressRetention(object): - RETAIN = "retain" - DISCARD = "discard" + :returns: Machine friendly representation + """ + return "" - def __init__(self, version, payload, account_sid, sid=None): - """ - Initialize the MessageInstance - - :returns: twilio.rest.api.v2010.account.message.MessageInstance - :rtype: twilio.rest.api.v2010.account.message.MessageInstance - """ - super(MessageInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'api_version': payload['api_version'], - 'body': payload['body'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'date_sent': deserialize.rfc2822_datetime(payload['date_sent']), - 'direction': payload['direction'], - 'error_code': deserialize.integer(payload['error_code']), - 'error_message': payload['error_message'], - 'from_': payload['from'], - 'messaging_service_sid': payload['messaging_service_sid'], - 'num_media': payload['num_media'], - 'num_segments': payload['num_segments'], - 'price': deserialize.decimal(payload['price']), - 'price_unit': payload['price_unit'], - 'sid': payload['sid'], - 'status': payload['status'], - 'subresource_uris': payload['subresource_uris'], - 'to': payload['to'], - 'uri': payload['uri'], - } - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } +class MessageList(ListResource): - @property - def _proxy(self): + def __init__(self, version: Version, account_sid: str): """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Initialize the MessageList - :returns: MessageContext for this MessageInstance - :rtype: twilio.rest.api.v2010.account.message.MessageContext - """ - if self._context is None: - self._context = MessageContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + :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. - @property - def account_sid(self): """ - :returns: The unique sid that identifies this account - :rtype: unicode - """ - return self._properties['account_sid'] + super().__init__(version) - @property - def api_version(self): - """ - :returns: The version of the Twilio API used to process the message. - :rtype: unicode - """ - return self._properties['api_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"}) - @property - def body(self): - """ - :returns: The text body of the message. Up to 1600 characters long. - :rtype: unicode - """ - return self._properties['body'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def date_created(self): - """ - :returns: The date this resource was created - :rtype: datetime - """ - return self._properties['date_created'] + headers["Accept"] = "application/json" - @property - def date_updated(self): - """ - :returns: The date this resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def date_sent(self): - """ - :returns: The date the message was sent - :rtype: datetime - """ - return self._properties['date_sent'] + return MessageInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def direction(self): - """ - :returns: The direction of the message - :rtype: MessageInstance.Direction - """ - return self._properties['direction'] + 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"}) - @property - def error_code(self): - """ - :returns: The error code associated with the message - :rtype: unicode - """ - return self._properties['error_code'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def error_message(self): - """ - :returns: Human readable description of the ErrorCode - :rtype: unicode - """ - return self._properties['error_message'] + headers["Accept"] = "application/json" - @property - def from_(self): - """ - :returns: The phone number that initiated the message - :rtype: unicode - """ - return self._properties['from_'] + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def messaging_service_sid(self): - """ - :returns: The messaging_service_sid - :rtype: unicode - """ - return self._properties['messaging_service_sid'] + return MessageInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def num_media(self): - """ - :returns: Number of media files associated with the message - :rtype: unicode + 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]: """ - return self._properties['num_media'] + 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. - @property - def num_segments(self): - """ - :returns: Indicates number of messages used to delivery the body - :rtype: unicode - """ - return self._properties['num_segments'] + :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) - @property - def price(self): - """ - :returns: The amount billed for the message - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['price'] + 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"], + ) - @property - def price_unit(self): - """ - :returns: The currency in which Price is measured - :rtype: unicode - """ - return self._properties['price_unit'] + return self._version.stream(page, limits["limit"]) - @property - def sid(self): + 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]: """ - :returns: A string that uniquely identifies this message - :rtype: unicode - """ - return self._properties['sid'] + 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. - @property - def status(self): - """ - :returns: The status of this message - :rtype: MessageInstance.Status - """ - return self._properties['status'] + :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) - @property - def subresource_uris(self): - """ - :returns: The URI for any subresources - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['subresource_uris'] + 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"], + ) - @property - def to(self): - """ - :returns: The phone number that received the message - :rtype: unicode - """ - return self._properties['to'] + return self._version.stream_async(page, limits["limit"]) - @property - def uri(self): + 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]: """ - :returns: The URI for this resource - :rtype: unicode + 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: """ - return self._properties['uri'] + 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 - def delete(self): + :returns: Page of MessageInstance """ - Deletes the 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, + } + ) - :returns: True if delete succeeds, False otherwise - :rtype: bool + headers = values.of({"Content-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 """ - return self._proxy.delete() + 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" - def fetch(self): + 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: """ - Fetch a MessageInstance + Retrieve a specific page of MessageInstance records from the API. + Request is executed immediately - :returns: Fetched MessageInstance - :rtype: twilio.rest.api.v2010.account.message.MessageInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return MessagePage(self._version, response, self._solution) - def update(self, body): + async def get_page_async(self, target_url: str) -> MessagePage: """ - Update the MessageInstance + Asynchronously retrieve a specific page of MessageInstance records from the API. + Request is executed immediately - :param unicode body: The body + :param target_url: API-generated URL for the requested results page - :returns: Updated MessageInstance - :rtype: twilio.rest.api.v2010.account.message.MessageInstance + :returns: Page of MessageInstance """ - return self._proxy.update(body, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagePage(self._version, response, self._solution) - @property - def media(self): + def get(self, sid: str) -> MessageContext: """ - Access the media + Constructs a MessageContext - :returns: twilio.rest.api.v2010.account.message.media.MediaList - :rtype: twilio.rest.api.v2010.account.message.media.MediaList + :param sid: The SID of the Message resource to be updated """ - return self._proxy.media + return MessageContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - @property - def feedback(self): + def __call__(self, sid: str) -> MessageContext: """ - Access the feedback + Constructs a MessageContext - :returns: twilio.rest.api.v2010.account.message.feedback.FeedbackList - :rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackList + :param sid: The SID of the Message resource to be updated """ - return self._proxy.feedback + return MessageContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/api/v2010/account/message/feedback.py b/twilio/rest/api/v2010/account/message/feedback.py index 73dbe49112..cda2de2ff6 100644 --- a/twilio/rest/api/v2010/account/message/feedback.py +++ b/twilio/rest/api/v2010/account/message/feedback.py @@ -1,201 +1,170 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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.page import Page +from twilio.base.version import Version -class FeedbackList(ListResource): - """ """ - - def __init__(self, version, account_sid, message_sid): - """ - Initialize the FeedbackList - - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param message_sid: The message_sid - - :returns: twilio.rest.api.v2010.account.message.feedback.FeedbackList - :rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackList - """ - super(FeedbackList, self).__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=values.unset): - """ - Create a new FeedbackInstance - - :param FeedbackInstance.Outcome outcome: The outcome - - :returns: Newly created FeedbackInstance - :rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackInstance - """ - data = values.of({'Outcome': outcome, }) +class FeedbackInstance(InstanceResource): - payload = self._version.create( - 'POST', - self._uri, - data=data, + 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") ) - - return FeedbackInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - message_sid=self._solution['message_sid'], + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class FeedbackPage(Page): - """ """ +class FeedbackList(ListResource): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str, message_sid: str): """ - Initialize the FeedbackPage + Initialize the FeedbackList - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The account_sid - :param message_sid: The message_sid + :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. - :returns: twilio.rest.api.v2010.account.message.feedback.FeedbackPage - :rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackPage """ - super(FeedbackPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def create( + self, outcome: Union["FeedbackInstance.Outcome", object] = values.unset + ) -> FeedbackInstance: """ - Build an instance of FeedbackInstance + Create the FeedbackInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.message.feedback.FeedbackInstance - :rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackInstance - """ - return FeedbackInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - message_sid=self._solution['message_sid'], - ) + :param outcome: - def __repr__(self): + :returns: The created FeedbackInstance """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str - """ - return '' + data = values.of( + { + "Outcome": outcome, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers["Content-Type"] = "application/x-www-form-urlencoded" -class FeedbackInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" - class Outcome(object): - CONFIRMED = "confirmed" - UMCONFIRMED = "umconfirmed" + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - def __init__(self, version, payload, account_sid, message_sid): - """ - Initialize the FeedbackInstance + return FeedbackInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + ) - :returns: twilio.rest.api.v2010.account.message.feedback.FeedbackInstance - :rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackInstance + async def create_async( + self, outcome: Union["FeedbackInstance.Outcome", object] = values.unset + ) -> FeedbackInstance: """ - super(FeedbackInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'message_sid': payload['message_sid'], - 'outcome': payload['outcome'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'uri': payload['uri'], - } + Asynchronously create the FeedbackInstance - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'message_sid': message_sid, } + :param outcome: - @property - def account_sid(self): + :returns: The created FeedbackInstance """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def message_sid(self): - """ - :returns: The message_sid - :rtype: unicode - """ - return self._properties['message_sid'] + data = values.of( + { + "Outcome": outcome, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def outcome(self): - """ - :returns: The outcome - :rtype: FeedbackInstance.Outcome - """ - return self._properties['outcome'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + headers["Accept"] = "application/json" - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def uri(self): - """ - :returns: The uri - :rtype: unicode - """ - return self._properties['uri'] + return FeedbackInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/api/v2010/account/message/media.py b/twilio/rest/api/v2010/account/message/media.py index 60b6df58c2..b5d2926d12 100644 --- a/twilio/rest/api/v2010/account/message/media.py +++ b/twilio/rest/api/v2010/account/message/media.py @@ -1,432 +1,564 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 MediaList(ListResource): - """ """ - - def __init__(self, version, account_sid, message_sid): - """ - Initialize the MediaList +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") - :param Version version: Version that contains the resource - :param account_sid: The unique sid that identifies this account - :param message_sid: A string that uniquely identifies this message + self._solution = { + "account_sid": account_sid, + "message_sid": message_sid, + "sid": sid or self.sid, + } + self._context: Optional[MediaContext] = None - :returns: twilio.rest.api.v2010.account.message.media.MediaList - :rtype: twilio.rest.api.v2010.account.message.media.MediaList + @property + def _proxy(self) -> "MediaContext": """ - super(MediaList, self).__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) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def stream(self, date_created_before=values.unset, date_created=values.unset, - date_created_after=values.unset, limit=None, page_size=None): + :returns: MediaContext for this 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_before: Filter by date created - :param datetime date_created: Filter by date created - :param datetime date_created_after: Filter by date created - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + 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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.message.media.MediaInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the MediaInstance - page = self.page( - date_created_before=date_created_before, - date_created=date_created, - date_created_after=date_created_after, - page_size=limits['page_size'], - ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, date_created_before=values.unset, date_created=values.unset, - date_created_after=values.unset, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists MediaInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the MediaInstance - :param datetime date_created_before: Filter by date created - :param datetime date_created: Filter by date created - :param datetime date_created_after: Filter by date created - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.message.media.MediaInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream( - date_created_before=date_created_before, - date_created=date_created, - date_created_after=date_created_after, - limit=limit, - page_size=page_size, - )) + return await self._proxy.delete_async() - def page(self, date_created_before=values.unset, date_created=values.unset, - date_created_after=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch(self) -> "MediaInstance": """ - Retrieve a single page of MediaInstance records from the API. - Request is executed immediately + Fetch the MediaInstance - :param datetime date_created_before: Filter by date created - :param datetime date_created: Filter by date created - :param datetime date_created_after: Filter by date created - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of MediaInstance - :rtype: twilio.rest.api.v2010.account.message.media.MediaPage + :returns: The fetched MediaInstance """ - params = values.of({ - 'DateCreated<': serialize.iso8601_datetime(date_created_before), - 'DateCreated': serialize.iso8601_datetime(date_created), - 'DateCreated>': serialize.iso8601_datetime(date_created_after), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + async def fetch_async(self) -> "MediaInstance": + """ + Asynchronous coroutine to fetch the MediaInstance - return MediaPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched MediaInstance """ - Retrieve a specific page of MediaInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_async() - :param str target_url: API-generated URL for the requested results page + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of MediaInstance - :rtype: twilio.rest.api.v2010.account.message.media.MediaPage + :returns: Machine friendly representation """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - return MediaPage(self._version, response, self._solution) - def get(self, sid): - """ - Constructs a MediaContext +class MediaContext(InstanceContext): - :param sid: Fetch by unique media Sid + def __init__(self, version: Version, account_sid: str, message_sid: str, sid: str): + """ + Initialize the MediaContext - :returns: twilio.rest.api.v2010.account.message.media.MediaContext - :rtype: twilio.rest.api.v2010.account.message.media.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. """ - return MediaContext( - self._version, - account_sid=self._solution['account_sid'], - message_sid=self._solution['message_sid'], - sid=sid, + 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 __call__(self, sid): + def delete(self) -> bool: """ - Constructs a MediaContext + Deletes the MediaInstance - :param sid: Fetch by unique media Sid - :returns: twilio.rest.api.v2010.account.message.media.MediaContext - :rtype: twilio.rest.api.v2010.account.message.media.MediaContext + :returns: True if delete succeeds, False otherwise """ - return MediaContext( - self._version, - account_sid=self._solution['account_sid'], - message_sid=self._solution['message_sid'], - sid=sid, - ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the MediaInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class MediaPage(Page): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> MediaInstance: """ - Initialize the MediaPage + Fetch the MediaInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The unique sid that identifies this account - :param message_sid: A string that uniquely identifies this message - :returns: twilio.rest.api.v2010.account.message.media.MediaPage - :rtype: twilio.rest.api.v2010.account.message.media.MediaPage + :returns: The fetched MediaInstance """ - super(MediaPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): - """ - Build an instance of MediaInstance + headers["Accept"] = "application/json" - :param dict payload: Payload response from the API + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.api.v2010.account.message.media.MediaInstance - :rtype: twilio.rest.api.v2010.account.message.media.MediaInstance - """ return MediaInstance( self._version, payload, - account_sid=self._solution['account_sid'], - message_sid=self._solution['message_sid'], + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + async def fetch_async(self) -> MediaInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the MediaInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched MediaInstance """ - return '' + headers = values.of({}) -class MediaContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, account_sid, message_sid, sid): - """ - Initialize the MediaContext + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param message_sid: The message_sid - :param sid: Fetch by unique media Sid + return MediaInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.api.v2010.account.message.media.MediaContext - :rtype: twilio.rest.api.v2010.account.message.media.MediaContext + def __repr__(self) -> str: """ - super(MediaContext, self).__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) + Provide a friendly representation - def delete(self): + :returns: Machine friendly representation """ - Deletes the MediaInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - def fetch(self): - """ - Fetch a MediaInstance +class MediaPage(Page): - :returns: Fetched MediaInstance - :rtype: twilio.rest.api.v2010.account.message.media.MediaInstance + def get_instance(self, payload: Dict[str, Any]) -> MediaInstance: """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) + 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'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" -class MediaInstance(InstanceResource): - """ """ +class MediaList(ListResource): - def __init__(self, version, payload, account_sid, message_sid, sid=None): + def __init__(self, version: Version, account_sid: str, message_sid: str): """ - Initialize the MediaInstance + Initialize the MediaList - :returns: twilio.rest.api.v2010.account.message.media.MediaInstance - :rtype: twilio.rest.api.v2010.account.message.media.MediaInstance - """ - super(MediaInstance, self).__init__(version) + :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. - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'content_type': payload['content_type'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'parent_sid': payload['parent_sid'], - 'sid': payload['sid'], - 'uri': payload['uri'], - } + """ + super().__init__(version) - # Context - self._context = None + # Path Solution self._solution = { - 'account_sid': account_sid, - 'message_sid': message_sid, - 'sid': sid or self._properties['sid'], + "account_sid": account_sid, + "message_sid": message_sid, } + self._uri = "/Accounts/{account_sid}/Messages/{message_sid}/Media.json".format( + **self._solution + ) - @property - def _proxy(self): + 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]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: MediaContext for this MediaInstance - :rtype: twilio.rest.api.v2010.account.message.media.MediaContext - """ - 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 + :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) - @property - def account_sid(self): - """ - :returns: The unique sid that identifies this account - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['account_sid'] + 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"], + ) - @property - def content_type(self): - """ - :returns: The default mime-type of the media - :rtype: unicode + 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]: """ - return self._properties['content_type'] + 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. - @property - def date_created(self): + :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 """ - :returns: The date this resource was created - :rtype: datetime + 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]: """ - return self._properties['date_created'] + Lists MediaInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def date_updated(self): + :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]: """ - :returns: The date this resource was last updated - :rtype: datetime + 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: """ - return self._properties['date_updated'] + Retrieve a single page of MediaInstance records from the API. + Request is executed immediately - @property - def parent_sid(self): + :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 """ - :returns: The unique id of the resource that created the media. - :rtype: unicode + 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 """ - return self._properties['parent_sid'] + 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, + } + ) - @property - def sid(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: A string that uniquely identifies this media - :rtype: unicode + 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 """ - return self._properties['sid'] + response = self._version.domain.twilio.request("GET", target_url) + return MediaPage(self._version, response, self._solution) - @property - def uri(self): + async def get_page_async(self, target_url: str) -> MediaPage: """ - :returns: The URI for this resource - :rtype: unicode + 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 """ - return self._properties['uri'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return MediaPage(self._version, response, self._solution) - def delete(self): + def get(self, sid: str) -> MediaContext: """ - Deletes the MediaInstance + Constructs a MediaContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the Media resource to fetch. """ - return self._proxy.delete() + return MediaContext( + self._version, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + sid=sid, + ) - def fetch(self): + def __call__(self, sid: str) -> MediaContext: """ - Fetch a MediaInstance + Constructs a MediaContext - :returns: Fetched MediaInstance - :rtype: twilio.rest.api.v2010.account.message.media.MediaInstance + :param sid: The Twilio-provided string that uniquely identifies the Media resource to fetch. """ - return self._proxy.fetch() + return MediaContext( + self._version, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/api/v2010/account/new_key.py b/twilio/rest/api/v2010/account/new_key.py index f3271fd69a..ba811ec14f 100644 --- a/twilio/rest/api/v2010/account/new_key.py +++ b/twilio/rest/api/v2010/account/new_key.py @@ -1,176 +1,144 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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.page import Page - - -class NewKeyList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the NewKeyList - - :param Version version: Version that contains the resource - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.new_key.NewKeyList - :rtype: twilio.rest.api.v2010.account.new_key.NewKeyList - """ - super(NewKeyList, self).__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=values.unset): - """ - Create a new NewKeyInstance +from twilio.base.version import Version - :param unicode friendly_name: The friendly_name - :returns: Newly created NewKeyInstance - :rtype: twilio.rest.api.v2010.account.new_key.NewKeyInstance - """ - data = values.of({'FriendlyName': friendly_name, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, +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") - return NewKeyInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + self._solution = { + "account_sid": account_sid, + } - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class NewKeyPage(Page): - """ """ +class NewKeyList(ListResource): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str): """ - Initialize the NewKeyPage + Initialize the NewKeyList - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: A 34 character string that uniquely identifies this resource. + :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. - :returns: twilio.rest.api.v2010.account.new_key.NewKeyPage - :rtype: twilio.rest.api.v2010.account.new_key.NewKeyPage """ - super(NewKeyPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Keys.json".format(**self._solution) - def get_instance(self, payload): + def create( + self, friendly_name: Union[str, object] = values.unset + ) -> NewKeyInstance: """ - Build an instance of NewKeyInstance + Create the NewKeyInstance - :param dict payload: Payload response from the API + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: twilio.rest.api.v2010.account.new_key.NewKeyInstance - :rtype: twilio.rest.api.v2010.account.new_key.NewKeyInstance + :returns: The created NewKeyInstance """ - return NewKeyInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - def __repr__(self): - """ - Provide a friendly representation + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" -class NewKeyInstance(InstanceResource): - """ """ + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - def __init__(self, version, payload, account_sid): - """ - Initialize the NewKeyInstance + return NewKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - :returns: twilio.rest.api.v2010.account.new_key.NewKeyInstance - :rtype: twilio.rest.api.v2010.account.new_key.NewKeyInstance + async def create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> NewKeyInstance: """ - super(NewKeyInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'friendly_name': payload['friendly_name'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'secret': payload['secret'], - } + Asynchronously create the NewKeyInstance - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + :returns: The created NewKeyInstance """ - return self._properties['sid'] - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Accept"] = "application/json" - @property - def secret(self): - """ - :returns: The secret - :rtype: unicode - """ - return self._properties['secret'] + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/api/v2010/account/new_signing_key.py b/twilio/rest/api/v2010/account/new_signing_key.py index eec5e86087..95341d31cb 100644 --- a/twilio/rest/api/v2010/account/new_signing_key.py +++ b/twilio/rest/api/v2010/account/new_signing_key.py @@ -1,176 +1,144 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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.page import Page - - -class NewSigningKeyList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the NewSigningKeyList - - :param Version version: Version that contains the resource - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyList - :rtype: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyList - """ - super(NewSigningKeyList, self).__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=values.unset): - """ - Create a new NewSigningKeyInstance +from twilio.base.version import Version - :param unicode friendly_name: The friendly_name - :returns: Newly created NewSigningKeyInstance - :rtype: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyInstance - """ - data = values.of({'FriendlyName': friendly_name, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, +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") - return NewSigningKeyInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + self._solution = { + "account_sid": account_sid, + } - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class NewSigningKeyPage(Page): - """ """ +class NewSigningKeyList(ListResource): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str): """ - Initialize the NewSigningKeyPage + Initialize the NewSigningKeyList - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: A 34 character string that uniquely identifies this resource. + :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. - :returns: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyPage - :rtype: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyPage """ - super(NewSigningKeyPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/SigningKeys.json".format(**self._solution) - def get_instance(self, payload): + def create( + self, friendly_name: Union[str, object] = values.unset + ) -> NewSigningKeyInstance: """ - Build an instance of NewSigningKeyInstance + Create the NewSigningKeyInstance - :param dict payload: Payload response from the API + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyInstance - :rtype: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyInstance + :returns: The created NewSigningKeyInstance """ - return NewSigningKeyInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - def __repr__(self): - """ - Provide a friendly representation + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" -class NewSigningKeyInstance(InstanceResource): - """ """ + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - def __init__(self, version, payload, account_sid): - """ - Initialize the NewSigningKeyInstance + return NewSigningKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - :returns: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyInstance - :rtype: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyInstance + async def create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> NewSigningKeyInstance: """ - super(NewSigningKeyInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'friendly_name': payload['friendly_name'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'secret': payload['secret'], - } + Asynchronously create the NewSigningKeyInstance - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + :returns: The created NewSigningKeyInstance """ - return self._properties['sid'] - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Accept"] = "application/json" - @property - def secret(self): - """ - :returns: The secret - :rtype: unicode - """ - return self._properties['secret'] + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/api/v2010/account/notification.py b/twilio/rest/api/v2010/account/notification.py index 5c81aba7d9..cd35efeabf 100644 --- a/twilio/rest/api/v2010/account/notification.py +++ b/twilio/rest/api/v2010/account/notification.py @@ -1,507 +1,540 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 NotificationList(ListResource): - """ """ +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 - def __init__(self, version, account_sid): + @property + def _proxy(self) -> "NotificationContext": """ - Initialize the NotificationList - - :param Version version: Version that contains the resource - :param account_sid: The unique sid that identifies this account + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: twilio.rest.api.v2010.account.notification.NotificationList - :rtype: twilio.rest.api.v2010.account.notification.NotificationList + :returns: NotificationContext for this NotificationInstance """ - super(NotificationList, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Notifications.json'.format(**self._solution) + if self._context is None: + self._context = NotificationContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - def stream(self, log=values.unset, message_date_before=values.unset, - message_date=values.unset, message_date_after=values.unset, - limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the NotificationInstance - :param unicode log: Filter by log level - :param date message_date_before: Filter by date - :param date message_date: Filter by date - :param date message_date_after: Filter by date - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.notification.NotificationInstance] + :returns: The fetched NotificationInstance """ - limits = self._version.read_limits(limit, page_size) - - page = self.page( - log=log, - message_date_before=message_date_before, - message_date=message_date, - message_date_after=message_date_after, - page_size=limits['page_size'], - ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) + return self._proxy.fetch() - def list(self, log=values.unset, message_date_before=values.unset, - message_date=values.unset, message_date_after=values.unset, limit=None, - page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the NotificationInstance - :param unicode log: Filter by log level - :param date message_date_before: Filter by date - :param date message_date: Filter by date - :param date message_date_after: Filter by date - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.notification.NotificationInstance] + :returns: The fetched NotificationInstance """ - return list(self.stream( - log=log, - message_date_before=message_date_before, - message_date=message_date, - message_date_after=message_date_after, - limit=limit, - page_size=page_size, - )) + return await self._proxy.fetch_async() - def page(self, log=values.unset, message_date_before=values.unset, - message_date=values.unset, message_date_after=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def __repr__(self) -> str: """ - Retrieve a single page of NotificationInstance records from the API. - Request is executed immediately + Provide a friendly representation - :param unicode log: Filter by log level - :param date message_date_before: Filter by date - :param date message_date: Filter by date - :param date message_date_after: Filter by date - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: Page of NotificationInstance - :rtype: twilio.rest.api.v2010.account.notification.NotificationPage - """ - params = values.of({ - 'Log': log, - 'MessageDate<': serialize.iso8601_date(message_date_before), - 'MessageDate': serialize.iso8601_date(message_date), - 'MessageDate>': serialize.iso8601_date(message_date_after), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - response = self._version.page( - 'GET', - self._uri, - params=params, - ) +class NotificationContext(InstanceContext): - return NotificationPage(self._version, response, self._solution) + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the NotificationContext - def get_page(self, target_url): + :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. """ - Retrieve a specific page of NotificationInstance records from the API. - Request is executed immediately + super().__init__(version) - :param str target_url: API-generated URL for the requested results page + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Notifications/{sid}.json".format( + **self._solution + ) - :returns: Page of NotificationInstance - :rtype: twilio.rest.api.v2010.account.notification.NotificationPage + def fetch(self) -> NotificationInstance: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Fetch the NotificationInstance - return NotificationPage(self._version, response, self._solution) - def get(self, sid): + :returns: The fetched NotificationInstance """ - Constructs a NotificationContext - :param sid: Fetch by unique notification Sid + headers = values.of({}) - :returns: twilio.rest.api.v2010.account.notification.NotificationContext - :rtype: twilio.rest.api.v2010.account.notification.NotificationContext - """ - return NotificationContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + headers["Accept"] = "application/json" - def __call__(self, sid): - """ - Constructs a NotificationContext + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :param sid: Fetch by unique notification Sid + return NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.api.v2010.account.notification.NotificationContext - :rtype: twilio.rest.api.v2010.account.notification.NotificationContext + async def fetch_async(self) -> NotificationInstance: """ - return NotificationContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + Asynchronous coroutine to fetch the NotificationInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: The fetched NotificationInstance """ - return '' + headers = values.of({}) -class NotificationPage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): - """ - Initialize the NotificationPage + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The unique sid that identifies this account + return NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.api.v2010.account.notification.NotificationPage - :rtype: twilio.rest.api.v2010.account.notification.NotificationPage + def __repr__(self) -> str: """ - super(NotificationPage, self).__init__(version, response) + Provide a friendly representation - # Path Solution - self._solution = solution + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - def get_instance(self, payload): + +class NotificationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> NotificationInstance: """ Build an instance of NotificationInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.notification.NotificationInstance - :rtype: twilio.rest.api.v2010.account.notification.NotificationInstance + :param payload: Payload response from the API """ - return NotificationInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + return NotificationInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class NotificationContext(InstanceContext): - """ """ +class NotificationList(ListResource): - def __init__(self, version, account_sid, sid): + def __init__(self, version: Version, account_sid: str): """ - Initialize the NotificationContext + Initialize the NotificationList - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param sid: Fetch by unique notification Sid + :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. - :returns: twilio.rest.api.v2010.account.notification.NotificationContext - :rtype: twilio.rest.api.v2010.account.notification.NotificationContext """ - super(NotificationContext, self).__init__(version) + 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): - """ - Fetch a NotificationInstance + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Notifications.json".format( + **self._solution + ) - :returns: Fetched NotificationInstance - :rtype: twilio.rest.api.v2010.account.notification.NotificationInstance + 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]: """ - params = values.of({}) + 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. - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) + :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) - return NotificationInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + :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"], ) - def delete(self): - """ - Deletes the NotificationInstance + return self._version.stream(page, limits["limit"]) - :returns: True if delete succeeds, False otherwise - :rtype: bool + 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]: """ - return self._version.delete('delete', self._uri) + 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. - def __repr__(self): - """ - Provide a friendly representation + :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: Machine friendly representation - :rtype: str + :returns: Generator that will yield up to limit results """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class NotificationInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid, sid=None): - """ - Initialize the NotificationInstance - - :returns: twilio.rest.api.v2010.account.notification.NotificationInstance - :rtype: twilio.rest.api.v2010.account.notification.NotificationInstance - """ - super(NotificationInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'api_version': payload['api_version'], - 'call_sid': payload['call_sid'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'error_code': payload['error_code'], - 'log': payload['log'], - 'message_date': deserialize.rfc2822_datetime(payload['message_date']), - 'message_text': payload['message_text'], - 'more_info': payload['more_info'], - 'request_method': payload['request_method'], - 'request_url': payload['request_url'], - 'sid': payload['sid'], - 'uri': payload['uri'], - 'request_variables': payload.get('request_variables'), - 'response_body': payload.get('response_body'), - 'response_headers': payload.get('response_headers'), - } + 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"], + ) - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } + return self._version.stream_async(page, limits["limit"]) - @property - def _proxy(self): + 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]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Lists NotificationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: NotificationContext for this NotificationInstance - :rtype: twilio.rest.api.v2010.account.notification.NotificationContext - """ - if self._context is None: - self._context = NotificationContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + :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, ) - return self._context + ) - @property - def account_sid(self): - """ - :returns: The unique sid that identifies this account - :rtype: unicode - """ - return self._properties['account_sid'] + 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. - @property - def api_version(self): - """ - :returns: The version of the Twilio API in use - :rtype: unicode + :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: """ - return self._properties['api_version'] + Retrieve a single page of NotificationInstance records from the API. + Request is executed immediately - @property - def call_sid(self): - """ - :returns: The string that uniquely identifies the call - :rtype: unicode - """ - return self._properties['call_sid'] + :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 - @property - def date_created(self): - """ - :returns: The date this resource was created - :rtype: datetime + :returns: Page of NotificationInstance """ - return self._properties['date_created'] + 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, + } + ) - @property - def date_updated(self): - """ - :returns: The date this resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def error_code(self): - """ - :returns: A unique error code corresponding to the notification - :rtype: unicode - """ - return self._properties['error_code'] + headers["Accept"] = "application/json" - @property - def log(self): - """ - :returns: An integer log level - :rtype: unicode - """ - return self._properties['log'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NotificationPage(self._version, response, self._solution) - @property - def message_date(self): - """ - :returns: The date the notification was generated - :rtype: datetime - """ - return self._properties['message_date'] + 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 - @property - def message_text(self): - """ - :returns: The text of the notification. - :rtype: unicode - """ - return self._properties['message_text'] + :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 - @property - def more_info(self): - """ - :returns: A URL for more information about the error code - :rtype: unicode + :returns: Page of NotificationInstance """ - return self._properties['more_info'] + 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, + } + ) - @property - def request_method(self): - """ - :returns: HTTP method used with the request url - :rtype: unicode - """ - return self._properties['request_method'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def request_url(self): - """ - :returns: URL of the resource that generated the notification - :rtype: unicode - """ - return self._properties['request_url'] + headers["Accept"] = "application/json" - @property - def request_variables(self): - """ - :returns: Twilio-generated HTTP variables sent to the server - :rtype: unicode - """ - return self._properties['request_variables'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NotificationPage(self._version, response, self._solution) - @property - def response_body(self): - """ - :returns: The HTTP body returned by your server. - :rtype: unicode + def get_page(self, target_url: str) -> NotificationPage: """ - return self._properties['response_body'] + Retrieve a specific page of NotificationInstance records from the API. + Request is executed immediately - @property - def response_headers(self): - """ - :returns: The HTTP headers returned by your server. - :rtype: unicode - """ - return self._properties['response_headers'] + :param target_url: API-generated URL for the requested results page - @property - def sid(self): - """ - :returns: A string that uniquely identifies this notification - :rtype: unicode + :returns: Page of NotificationInstance """ - return self._properties['sid'] + response = self._version.domain.twilio.request("GET", target_url) + return NotificationPage(self._version, response, self._solution) - @property - def uri(self): + async def get_page_async(self, target_url: str) -> NotificationPage: """ - :returns: The URI for this resource - :rtype: unicode + 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 """ - return self._properties['uri'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return NotificationPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> NotificationContext: """ - Fetch a NotificationInstance + Constructs a NotificationContext - :returns: Fetched NotificationInstance - :rtype: twilio.rest.api.v2010.account.notification.NotificationInstance + :param sid: The Twilio-provided string that uniquely identifies the Notification resource to fetch. """ - return self._proxy.fetch() + return NotificationContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def delete(self): + def __call__(self, sid: str) -> NotificationContext: """ - Deletes the NotificationInstance + Constructs a NotificationContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the Notification resource to fetch. """ - return self._proxy.delete() + return NotificationContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/api/v2010/account/outgoing_caller_id.py b/twilio/rest/api/v2010/account/outgoing_caller_id.py index 5a0aeb0cfe..eeb9954c75 100644 --- a/twilio/rest/api/v2010/account/outgoing_caller_id.py +++ b/twilio/rest/api/v2010/account/outgoing_caller_id.py @@ -1,436 +1,620 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 OutgoingCallerIdList(ListResource): - """ """ +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 - def __init__(self, version, account_sid): + @property + def _proxy(self) -> "OutgoingCallerIdContext": """ - Initialize the OutgoingCallerIdList - - :param Version version: Version that contains the resource - :param account_sid: The unique sid that identifies this account + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdList - :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdList + :returns: OutgoingCallerIdContext for this OutgoingCallerIdInstance """ - super(OutgoingCallerIdList, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/OutgoingCallerIds.json'.format(**self._solution) + if self._context is None: + self._context = OutgoingCallerIdContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - def stream(self, phone_number=values.unset, friendly_name=values.unset, - limit=None, page_size=None): + def delete(self) -> bool: """ - 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. + Deletes the OutgoingCallerIdInstance - :param unicode phone_number: Filter by phone number - :param unicode friendly_name: Filter by friendly name - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdInstance] + :returns: True if delete succeeds, False otherwise """ - 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'], limits['page_limit']) + return self._proxy.delete() - def list(self, phone_number=values.unset, friendly_name=values.unset, - limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists OutgoingCallerIdInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the OutgoingCallerIdInstance - :param unicode phone_number: Filter by phone number - :param unicode friendly_name: Filter by friendly name - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream( - phone_number=phone_number, - friendly_name=friendly_name, - limit=limit, - page_size=page_size, - )) + return await self._proxy.delete_async() - def page(self, phone_number=values.unset, friendly_name=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "OutgoingCallerIdInstance": """ - Retrieve a single page of OutgoingCallerIdInstance records from the API. - Request is executed immediately + Fetch the OutgoingCallerIdInstance - :param unicode phone_number: Filter by phone number - :param unicode friendly_name: Filter by friendly name - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of OutgoingCallerIdInstance - :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdPage + :returns: The fetched OutgoingCallerIdInstance """ - params = values.of({ - 'PhoneNumber': phone_number, - 'FriendlyName': friendly_name, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return OutgoingCallerIdPage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "OutgoingCallerIdInstance": """ - Retrieve a specific page of OutgoingCallerIdInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the OutgoingCallerIdInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of OutgoingCallerIdInstance - :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdPage + :returns: The fetched OutgoingCallerIdInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return await self._proxy.fetch_async() - return OutgoingCallerIdPage(self._version, response, self._solution) - - def get(self, sid): + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> "OutgoingCallerIdInstance": """ - Constructs a OutgoingCallerIdContext + Update the OutgoingCallerIdInstance - :param sid: Fetch by unique outgoing-caller-id Sid + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdContext - :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdContext + :returns: The updated OutgoingCallerIdInstance """ - return OutgoingCallerIdContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.update( + friendly_name=friendly_name, + ) - def __call__(self, sid): + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "OutgoingCallerIdInstance": """ - Constructs a OutgoingCallerIdContext + Asynchronous coroutine to update the OutgoingCallerIdInstance - :param sid: Fetch by unique outgoing-caller-id Sid + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdContext - :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdContext + :returns: The updated OutgoingCallerIdInstance """ - return OutgoingCallerIdContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return await self._proxy.update_async( + friendly_name=friendly_name, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class OutgoingCallerIdPage(Page): - """ """ +class OutgoingCallerIdContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str, sid: str): """ - Initialize the OutgoingCallerIdPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The unique sid that identifies this account + Initialize the OutgoingCallerIdContext - :returns: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdPage - :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdPage + :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(OutgoingCallerIdPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/OutgoingCallerIds/{sid}.json".format( + **self._solution + ) - def get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of OutgoingCallerIdInstance + Deletes the OutgoingCallerIdInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdInstance - :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdInstance + :returns: True if delete succeeds, False otherwise """ - return OutgoingCallerIdInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the OutgoingCallerIdInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class OutgoingCallerIdContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, account_sid, sid): + def fetch(self) -> OutgoingCallerIdInstance: """ - Initialize the OutgoingCallerIdContext + Fetch the OutgoingCallerIdInstance - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param sid: Fetch by unique outgoing-caller-id Sid - :returns: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdContext - :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdContext + :returns: The fetched OutgoingCallerIdInstance """ - super(OutgoingCallerIdContext, self).__init__(version) - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/OutgoingCallerIds/{sid}.json'.format(**self._solution) + headers = values.of({}) - def fetch(self): + 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: """ - Fetch a OutgoingCallerIdInstance + Asynchronous coroutine to fetch the OutgoingCallerIdInstance - :returns: Fetched OutgoingCallerIdInstance - :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdInstance + + :returns: The fetched OutgoingCallerIdInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def update(self, friendly_name=values.unset): + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> OutgoingCallerIdInstance: """ Update the OutgoingCallerIdInstance - :param unicode friendly_name: A human readable description of the caller ID + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: Updated OutgoingCallerIdInstance - :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdInstance + :returns: The updated OutgoingCallerIdInstance """ - data = values.of({'FriendlyName': friendly_name, }) + + 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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) return OutgoingCallerIdInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> OutgoingCallerIdInstance: """ - Deletes the OutgoingCallerIdInstance + Asynchronous coroutine to update the OutgoingCallerIdInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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._version.delete('delete', self._uri) - def __repr__(self): + 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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class OutgoingCallerIdInstance(InstanceResource): - """ """ +class OutgoingCallerIdPage(Page): - def __init__(self, version, payload, account_sid, sid=None): + def get_instance(self, payload: Dict[str, Any]) -> OutgoingCallerIdInstance: """ - Initialize the OutgoingCallerIdInstance + Build an instance of OutgoingCallerIdInstance - :returns: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdInstance - :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdInstance + :param payload: Payload response from the API """ - super(OutgoingCallerIdInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'friendly_name': payload['friendly_name'], - 'account_sid': payload['account_sid'], - 'phone_number': payload['phone_number'], - 'uri': payload['uri'], - } - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } + return OutgoingCallerIdInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def _proxy(self): + def __repr__(self) -> str: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Provide a friendly representation - :returns: OutgoingCallerIdContext for this OutgoingCallerIdInstance - :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdContext + :returns: Machine friendly representation """ - if self._context is None: - self._context = OutgoingCallerIdContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + return "" - @property - def sid(self): - """ - :returns: A string that uniquely identifies this outgoing-caller-ids - :rtype: unicode + +class OutgoingCallerIdList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - return self._properties['sid'] + 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. - @property - def date_created(self): """ - :returns: The date this resource was created - :rtype: datetime + 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]: """ - return self._properties['date_created'] + 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. - @property - def date_updated(self): + :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 """ - :returns: The date this resource was last updated - :rtype: datetime + 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]: """ - return self._properties['date_updated'] + 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. - @property - def friendly_name(self): + :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 """ - :returns: A human readable description for this resource - :rtype: unicode + 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]: """ - return self._properties['friendly_name'] + Lists OutgoingCallerIdInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def account_sid(self): + :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]: """ - :returns: The unique sid that identifies this account - :rtype: unicode + 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: """ - return self._properties['account_sid'] + Retrieve a single page of OutgoingCallerIdInstance records from the API. + Request is executed immediately - @property - def phone_number(self): + :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 """ - :returns: The incoming phone number - :rtype: unicode + 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: """ - return self._properties['phone_number'] + Asynchronously retrieve a single page of OutgoingCallerIdInstance records from the API. + Request is executed immediately - @property - def uri(self): + :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 """ - :returns: The URI for this resource - :rtype: unicode + 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: """ - return self._properties['uri'] + 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 - def fetch(self): + :returns: Page of OutgoingCallerIdInstance """ - Fetch a OutgoingCallerIdInstance + response = self._version.domain.twilio.request("GET", target_url) + return OutgoingCallerIdPage(self._version, response, self._solution) - :returns: Fetched OutgoingCallerIdInstance - :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdInstance + async def get_page_async(self, target_url: str) -> OutgoingCallerIdPage: """ - return self._proxy.fetch() + 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 - def update(self, friendly_name=values.unset): + :returns: Page of OutgoingCallerIdInstance """ - Update the OutgoingCallerIdInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return OutgoingCallerIdPage(self._version, response, self._solution) - :param unicode friendly_name: A human readable description of the caller ID + def get(self, sid: str) -> OutgoingCallerIdContext: + """ + Constructs a OutgoingCallerIdContext - :returns: Updated OutgoingCallerIdInstance - :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdInstance + :param sid: The Twilio-provided string that uniquely identifies the OutgoingCallerId resource to update. """ - return self._proxy.update(friendly_name=friendly_name, ) + return OutgoingCallerIdContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def delete(self): + def __call__(self, sid: str) -> OutgoingCallerIdContext: """ - Deletes the OutgoingCallerIdInstance + Constructs a OutgoingCallerIdContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the OutgoingCallerId resource to update. """ - return self._proxy.delete() + return OutgoingCallerIdContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/api/v2010/account/queue/__init__.py b/twilio/rest/api/v2010/account/queue/__init__.py index 3975a91ac2..e76fda1259 100644 --- a/twilio/rest/api/v2010/account/queue/__init__.py +++ b/twilio/rest/api/v2010/account/queue/__init__.py @@ -1,482 +1,687 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 QueueList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the QueueList +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")) - :param Version version: Version that contains the resource - :param account_sid: The account_sid + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[QueueContext] = None - :returns: twilio.rest.api.v2010.account.queue.QueueList - :rtype: twilio.rest.api.v2010.account.queue.QueueList + @property + def _proxy(self) -> "QueueContext": """ - super(QueueList, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Queues.json'.format(**self._solution) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def stream(self, limit=None, page_size=None): + :returns: QueueContext for this 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + if self._context is None: + self._context = QueueContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.queue.QueueInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the QueueInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists QueueInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the QueueInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.queue.QueueInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "QueueInstance": """ - Retrieve a single page of QueueInstance records from the API. - Request is executed immediately + Fetch the QueueInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of QueueInstance - :rtype: twilio.rest.api.v2010.account.queue.QueuePage + :returns: The fetched QueueInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return QueuePage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "QueueInstance": """ - Retrieve a specific page of QueueInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the QueueInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of QueueInstance - :rtype: twilio.rest.api.v2010.account.queue.QueuePage + :returns: The fetched QueueInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return await self._proxy.fetch_async() - return QueuePage(self._version, response, self._solution) - - def create(self, friendly_name, max_size=values.unset): + def update( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> "QueueInstance": """ - Create a new QueueInstance + Update the QueueInstance - :param unicode friendly_name: A user-provided string that identifies this queue. - :param unicode max_size: The max number of calls allowed in the queue + :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: Newly created QueueInstance - :rtype: twilio.rest.api.v2010.account.queue.QueueInstance + :returns: The updated QueueInstance """ - data = values.of({'FriendlyName': friendly_name, 'MaxSize': max_size, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, + return self._proxy.update( + friendly_name=friendly_name, + max_size=max_size, ) - return QueueInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - def get(self, sid): + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> "QueueInstance": """ - Constructs a QueueContext + Asynchronous coroutine to update the QueueInstance - :param sid: Fetch by unique queue Sid + :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: twilio.rest.api.v2010.account.queue.QueueContext - :rtype: twilio.rest.api.v2010.account.queue.QueueContext + :returns: The updated QueueInstance """ - return QueueContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return await self._proxy.update_async( + friendly_name=friendly_name, + max_size=max_size, + ) - def __call__(self, sid): + @property + def members(self) -> MemberList: """ - Constructs a QueueContext - - :param sid: Fetch by unique queue Sid - - :returns: twilio.rest.api.v2010.account.queue.QueueContext - :rtype: twilio.rest.api.v2010.account.queue.QueueContext + Access the members """ - return QueueContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.members - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class QueuePage(Page): - """ """ +class QueueContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str, sid: str): """ - Initialize the QueuePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The account_sid + Initialize the QueueContext - :returns: twilio.rest.api.v2010.account.queue.QueuePage - :rtype: twilio.rest.api.v2010.account.queue.QueuePage + :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(QueuePage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Queues/{sid}.json".format(**self._solution) - def get_instance(self, payload): + self._members: Optional[MemberList] = None + + def delete(self) -> bool: """ - Build an instance of QueueInstance + Deletes the QueueInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.api.v2010.account.queue.QueueInstance - :rtype: twilio.rest.api.v2010.account.queue.QueueInstance + :returns: True if delete succeeds, False otherwise """ - return QueueInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the QueueInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class QueueContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, account_sid, sid): + def fetch(self) -> QueueInstance: """ - Initialize the QueueContext + Fetch the QueueInstance - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param sid: Fetch by unique queue Sid - :returns: twilio.rest.api.v2010.account.queue.QueueContext - :rtype: twilio.rest.api.v2010.account.queue.QueueContext + :returns: The fetched QueueInstance """ - super(QueueContext, self).__init__(version) - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/Queues/{sid}.json'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - # Dependents - self._members = None + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return QueueInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> QueueInstance: """ - Fetch a QueueInstance + Asynchronous coroutine to fetch the QueueInstance + - :returns: Fetched QueueInstance - :rtype: twilio.rest.api.v2010.account.queue.QueueInstance + :returns: The fetched QueueInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def update(self, friendly_name=values.unset, max_size=values.unset): + def update( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> QueueInstance: """ Update the QueueInstance - :param unicode friendly_name: A human readable description of the queue - :param unicode max_size: The max number of members allowed in the queue + :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: Updated QueueInstance - :rtype: twilio.rest.api.v2010.account.queue.QueueInstance + :returns: The updated QueueInstance """ - data = values.of({'FriendlyName': friendly_name, 'MaxSize': max_size, }) + + 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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) return QueueInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> QueueInstance: """ - Deletes the QueueInstance + Asynchronous coroutine to update the QueueInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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._version.delete('delete', self._uri) + + 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): + def members(self) -> MemberList: """ Access the members - - :returns: twilio.rest.api.v2010.account.queue.member.MemberList - :rtype: twilio.rest.api.v2010.account.queue.member.MemberList """ if self._members is None: self._members = MemberList( self._version, - account_sid=self._solution['account_sid'], - queue_sid=self._solution['sid'], + self._solution["account_sid"], + self._solution["sid"], ) return self._members - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class QueueInstance(InstanceResource): - """ """ +class QueuePage(Page): - def __init__(self, version, payload, account_sid, sid=None): + def get_instance(self, payload: Dict[str, Any]) -> QueueInstance: """ - Initialize the QueueInstance + Build an instance of QueueInstance - :returns: twilio.rest.api.v2010.account.queue.QueueInstance - :rtype: twilio.rest.api.v2010.account.queue.QueueInstance + :param payload: Payload response from the API """ - super(QueueInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'average_wait_time': deserialize.integer(payload['average_wait_time']), - 'current_size': deserialize.integer(payload['current_size']), - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'friendly_name': payload['friendly_name'], - 'max_size': deserialize.integer(payload['max_size']), - 'sid': payload['sid'], - 'uri': payload['uri'], - } - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } + return QueueInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def _proxy(self): + def __repr__(self) -> str: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Provide a friendly representation - :returns: QueueContext for this QueueInstance - :rtype: twilio.rest.api.v2010.account.queue.QueueContext + :returns: Machine friendly representation """ - if self._context is None: - self._context = QueueContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + return "" - @property - def account_sid(self): + +class QueueList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - :returns: The account_sid - :rtype: unicode + 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. + """ - return self._properties['account_sid'] + super().__init__(version) - @property - def average_wait_time(self): + # 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: """ - :returns: Average wait time of members in the queue - :rtype: unicode + 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 """ - return self._properties['average_wait_time'] - @property - def current_size(self): + 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: """ - :returns: The count of calls currently in the queue. - :rtype: unicode + 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 """ - return self._properties['current_size'] - @property - def date_created(self): + 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]: """ - :returns: The date_created - :rtype: datetime + 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 """ - return self._properties['date_created'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def date_updated(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[QueueInstance]: """ - :returns: The date_updated - :rtype: datetime + 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 """ - return self._properties['date_updated'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def friendly_name(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[QueueInstance]: """ - :returns: A user-provided string that identifies this queue. - :rtype: unicode + 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 self._properties['friendly_name'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def max_size(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[QueueInstance]: """ - :returns: The max number of calls allowed in the queue - :rtype: unicode + 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 self._properties['max_size'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def sid(self): + 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: """ - :returns: A string that uniquely identifies this queue - :rtype: unicode + 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 """ - return self._properties['sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def uri(self): + headers = values.of({"Content-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: """ - :returns: The uri - :rtype: unicode + 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 """ - return self._properties['uri'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def fetch(self): + 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: """ - Fetch a QueueInstance + Retrieve a specific page of QueueInstance records from the API. + Request is executed immediately - :returns: Fetched QueueInstance - :rtype: twilio.rest.api.v2010.account.queue.QueueInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of QueueInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return QueuePage(self._version, response, self._solution) - def update(self, friendly_name=values.unset, max_size=values.unset): + async def get_page_async(self, target_url: str) -> QueuePage: """ - Update the QueueInstance + Asynchronously retrieve a specific page of QueueInstance records from the API. + Request is executed immediately - :param unicode friendly_name: A human readable description of the queue - :param unicode max_size: The max number of members allowed in the queue + :param target_url: API-generated URL for the requested results page - :returns: Updated QueueInstance - :rtype: twilio.rest.api.v2010.account.queue.QueueInstance + :returns: Page of QueueInstance """ - return self._proxy.update(friendly_name=friendly_name, max_size=max_size, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return QueuePage(self._version, response, self._solution) - def delete(self): + def get(self, sid: str) -> QueueContext: """ - Deletes the QueueInstance + Constructs a QueueContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the Queue resource to update """ - return self._proxy.delete() + return QueueContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - @property - def members(self): + def __call__(self, sid: str) -> QueueContext: """ - Access the members + Constructs a QueueContext - :returns: twilio.rest.api.v2010.account.queue.member.MemberList - :rtype: twilio.rest.api.v2010.account.queue.member.MemberList + :param sid: The Twilio-provided string that uniquely identifies the Queue resource to update """ - return self._proxy.members + return QueueContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/api/v2010/account/queue/member.py b/twilio/rest/api/v2010/account/queue/member.py index e5dec61924..30ff4abbc7 100644 --- a/twilio/rest/api/v2010/account/queue/member.py +++ b/twilio/rest/api/v2010/account/queue/member.py @@ -1,403 +1,564 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 MemberList(ListResource): - """ """ - - def __init__(self, version, account_sid, queue_sid): - """ - Initialize the MemberList +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") - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param queue_sid: A string that uniquely identifies this queue + self._solution = { + "account_sid": account_sid, + "queue_sid": queue_sid, + "call_sid": call_sid or self.call_sid, + } + self._context: Optional[MemberContext] = None - :returns: twilio.rest.api.v2010.account.queue.member.MemberList - :rtype: twilio.rest.api.v2010.account.queue.member.MemberList + @property + def _proxy(self) -> "MemberContext": """ - super(MemberList, self).__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) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def stream(self, limit=None, page_size=None): + :returns: MemberContext for this 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + 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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.queue.member.MemberInstance] + def fetch(self) -> "MemberInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the MemberInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched MemberInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the MemberInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.queue.member.MemberInstance] + :returns: The fetched MemberInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def update( + self, url: str, method: Union[str, object] = values.unset + ) -> "MemberInstance": """ - Retrieve a single page of MemberInstance records from the API. - Request is executed immediately + Update the MemberInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :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: Page of MemberInstance - :rtype: twilio.rest.api.v2010.account.queue.member.MemberPage + :returns: The updated MemberInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + return self._proxy.update( + url=url, + method=method, ) - return MemberPage(self._version, response, self._solution) - - def get_page(self, target_url): + async def update_async( + self, url: str, method: Union[str, object] = values.unset + ) -> "MemberInstance": """ - Retrieve a specific page of MemberInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the MemberInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of MemberInstance - :rtype: twilio.rest.api.v2010.account.queue.member.MemberPage + :returns: The updated MemberInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + url=url, + method=method, ) - return MemberPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, call_sid): + :returns: Machine friendly representation """ - Constructs a MemberContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param call_sid: The call_sid - :returns: twilio.rest.api.v2010.account.queue.member.MemberContext - :rtype: twilio.rest.api.v2010.account.queue.member.MemberContext - """ - return MemberContext( - self._version, - account_sid=self._solution['account_sid'], - queue_sid=self._solution['queue_sid'], - call_sid=call_sid, - ) +class MemberContext(InstanceContext): - def __call__(self, call_sid): + def __init__( + self, version: Version, account_sid: str, queue_sid: str, call_sid: str + ): """ - Constructs a MemberContext - - :param call_sid: The call_sid + Initialize the MemberContext - :returns: twilio.rest.api.v2010.account.queue.member.MemberContext - :rtype: twilio.rest.api.v2010.account.queue.member.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. """ - return MemberContext( - self._version, - account_sid=self._solution['account_sid'], - queue_sid=self._solution['queue_sid'], - call_sid=call_sid, + 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 __repr__(self): + def fetch(self) -> MemberInstance: """ - Provide a friendly representation + Fetch the MemberInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched MemberInstance """ - return '' + headers = values.of({}) -class MemberPage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): - """ - Initialize the MemberPage + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The account_sid - :param queue_sid: A string that uniquely identifies this queue + return MemberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], + ) - :returns: twilio.rest.api.v2010.account.queue.member.MemberPage - :rtype: twilio.rest.api.v2010.account.queue.member.MemberPage + async def fetch_async(self) -> MemberInstance: """ - super(MemberPage, self).__init__(version, response) + Asynchronous coroutine to fetch the MemberInstance - # Path Solution - self._solution = solution - def get_instance(self, payload): + :returns: The fetched MemberInstance """ - Build an instance of MemberInstance - :param dict payload: Payload response from the API + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: twilio.rest.api.v2010.account.queue.member.MemberInstance - :rtype: twilio.rest.api.v2010.account.queue.member.MemberInstance - """ return MemberInstance( self._version, payload, - account_sid=self._solution['account_sid'], - queue_sid=self._solution['queue_sid'], + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], ) - def __repr__(self): + def update( + self, url: str, method: Union[str, object] = values.unset + ) -> MemberInstance: """ - Provide a friendly representation + Update the MemberInstance - :returns: Machine friendly representation - :rtype: str + :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 '' + data = values.of( + { + "Url": url, + "Method": method, + } + ) + headers = values.of({}) -class MemberContext(InstanceContext): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, account_sid, queue_sid, call_sid): - """ - Initialize the MemberContext + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param queue_sid: The Queue in which to find the members - :param call_sid: The call_sid + return MemberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], + ) - :returns: twilio.rest.api.v2010.account.queue.member.MemberContext - :rtype: twilio.rest.api.v2010.account.queue.member.MemberContext + async def update_async( + self, url: str, method: Union[str, object] = values.unset + ) -> MemberInstance: """ - super(MemberContext, self).__init__(version) + Asynchronous coroutine to update the MemberInstance - # 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) + :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. - def fetch(self): + :returns: The updated MemberInstance """ - Fetch a MemberInstance - :returns: Fetched MemberInstance - :rtype: twilio.rest.api.v2010.account.queue.member.MemberInstance - """ - params = values.of({}) + 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.fetch( - 'GET', - self._uri, - params=params, + 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'], + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], ) - def update(self, url, method): + def __repr__(self) -> str: """ - Update the MemberInstance - - :param unicode url: The url - :param unicode method: The method + Provide a friendly representation - :returns: Updated MemberInstance - :rtype: twilio.rest.api.v2010.account.queue.member.MemberInstance + :returns: Machine friendly representation """ - data = values.of({'Url': url, 'Method': method, }) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) +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'], - call_sid=self._solution['call_sid'], + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" -class MemberInstance(InstanceResource): - """ """ +class MemberList(ListResource): - def __init__(self, version, payload, account_sid, queue_sid, call_sid=None): + def __init__(self, version: Version, account_sid: str, queue_sid: str): """ - Initialize the MemberInstance + Initialize the MemberList - :returns: twilio.rest.api.v2010.account.queue.member.MemberInstance - :rtype: twilio.rest.api.v2010.account.queue.member.MemberInstance - """ - super(MemberInstance, self).__init__(version) + :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 - # Marshaled Properties - self._properties = { - 'call_sid': payload['call_sid'], - 'date_enqueued': deserialize.rfc2822_datetime(payload['date_enqueued']), - 'position': deserialize.integer(payload['position']), - 'uri': payload['uri'], - 'wait_time': deserialize.integer(payload['wait_time']), - } + """ + super().__init__(version) - # Context - self._context = None + # Path Solution self._solution = { - 'account_sid': account_sid, - 'queue_sid': queue_sid, - 'call_sid': call_sid or self._properties['call_sid'], + "account_sid": account_sid, + "queue_sid": queue_sid, } + self._uri = "/Accounts/{account_sid}/Queues/{queue_sid}/Members.json".format( + **self._solution + ) - @property - def _proxy(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MemberInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: MemberContext for this MemberInstance - :rtype: twilio.rest.api.v2010.account.queue.member.MemberContext + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - 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 + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def call_sid(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MemberInstance]: """ - :returns: Unique string that identifies this resource - :rtype: unicode + 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 """ - return self._properties['call_sid'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def date_enqueued(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: """ - :returns: The date the member was enqueued - :rtype: datetime + 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 self._properties['date_enqueued'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def position(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: """ - :returns: This member's current position in the queue. - :rtype: unicode + 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 self._properties['position'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def uri(self): + 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: """ - :returns: The uri - :rtype: unicode + 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 """ - return self._properties['uri'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def wait_time(self): + headers = values.of({"Content-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: """ - :returns: The number of seconds the member has been in the queue. - :rtype: unicode + 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 """ - return self._properties['wait_time'] + response = self._version.domain.twilio.request("GET", target_url) + return MemberPage(self._version, response, self._solution) - def fetch(self): + async def get_page_async(self, target_url: str) -> MemberPage: """ - Fetch a MemberInstance + 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: Fetched MemberInstance - :rtype: twilio.rest.api.v2010.account.queue.member.MemberInstance + :returns: Page of MemberInstance """ - return self._proxy.fetch() + response = await self._version.domain.twilio.request_async("GET", target_url) + return MemberPage(self._version, response, self._solution) - def update(self, url, method): + def get(self, call_sid: str) -> MemberContext: """ - Update the MemberInstance + Constructs a MemberContext - :param unicode url: The url - :param unicode method: The method + :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, + ) - :returns: Updated MemberInstance - :rtype: twilio.rest.api.v2010.account.queue.member.MemberInstance + def __call__(self, call_sid: str) -> MemberContext: """ - return self._proxy.update(url, method, ) + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/api/v2010/account/recording/__init__.py b/twilio/rest/api/v2010/account/recording/__init__.py index 2beccee701..807fb3ca6e 100644 --- a/twilio/rest/api/v2010/account/recording/__init__.py +++ b/twilio/rest/api/v2010/account/recording/__init__.py @@ -1,588 +1,720 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 RecordingList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the RecordingList +class RecordingInstance(InstanceResource): - :param Version version: Version that contains the resource - :param account_sid: The unique sid that identifies this account + class Source(object): + DIALVERB = "DialVerb" + CONFERENCE = "Conference" + OUTBOUNDAPI = "OutboundAPI" + TRUNKING = "Trunking" + RECORDVERB = "RecordVerb" + STARTCALLRECORDINGAPI = "StartCallRecordingAPI" + STARTCONFERENCERECORDINGAPI = "StartConferenceRecordingAPI" - :returns: twilio.rest.api.v2010.account.recording.RecordingList - :rtype: twilio.rest.api.v2010.account.recording.RecordingList - """ - super(RecordingList, self).__init__(version) + 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") - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Recordings.json'.format(**self._solution) + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[RecordingContext] = None - def stream(self, date_created_before=values.unset, date_created=values.unset, - date_created_after=values.unset, call_sid=values.unset, - conference_sid=values.unset, limit=None, page_size=None): + @property + def _proxy(self) -> "RecordingContext": """ - 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. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param datetime date_created_before: Filter by date created - :param datetime date_created: Filter by date created - :param datetime date_created_after: Filter by date created - :param unicode call_sid: Filter by call_sid - :param unicode conference_sid: The conference_sid - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.recording.RecordingInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the RecordingInstance - page = self.page( - date_created_before=date_created_before, - date_created=date_created, - date_created_after=date_created_after, - call_sid=call_sid, - conference_sid=conference_sid, - page_size=limits['page_size'], - ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, date_created_before=values.unset, date_created=values.unset, - date_created_after=values.unset, call_sid=values.unset, - conference_sid=values.unset, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists RecordingInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the RecordingInstance - :param datetime date_created_before: Filter by date created - :param datetime date_created: Filter by date created - :param datetime date_created_after: Filter by date created - :param unicode call_sid: Filter by call_sid - :param unicode conference_sid: The conference_sid - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.recording.RecordingInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream( - date_created_before=date_created_before, - date_created=date_created, - date_created_after=date_created_after, - call_sid=call_sid, - conference_sid=conference_sid, - limit=limit, - page_size=page_size, - )) + return await self._proxy.delete_async() - def page(self, date_created_before=values.unset, date_created=values.unset, - date_created_after=values.unset, call_sid=values.unset, - conference_sid=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> "RecordingInstance": """ - Retrieve a single page of RecordingInstance records from the API. - Request is executed immediately + Fetch the RecordingInstance - :param datetime date_created_before: Filter by date created - :param datetime date_created: Filter by date created - :param datetime date_created_after: Filter by date created - :param unicode call_sid: Filter by call_sid - :param unicode conference_sid: The conference_sid - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :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: Page of RecordingInstance - :rtype: twilio.rest.api.v2010.account.recording.RecordingPage - """ - params = values.of({ - 'DateCreated<': serialize.iso8601_datetime(date_created_before), - 'DateCreated': serialize.iso8601_datetime(date_created), - 'DateCreated>': serialize.iso8601_datetime(date_created_after), - 'CallSid': call_sid, - 'ConferenceSid': conference_sid, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + :returns: The fetched RecordingInstance + """ + return self._proxy.fetch( + include_soft_deleted=include_soft_deleted, ) - return RecordingPage(self._version, response, self._solution) - - def get_page(self, target_url): + async def fetch_async( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> "RecordingInstance": """ - Retrieve a specific page of RecordingInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the RecordingInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of RecordingInstance - :rtype: twilio.rest.api.v2010.account.recording.RecordingPage + :returns: The fetched RecordingInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.fetch_async( + include_soft_deleted=include_soft_deleted, ) - return RecordingPage(self._version, response, self._solution) - - def get(self, sid): + @property + def add_on_results(self) -> AddOnResultList: """ - Constructs a RecordingContext - - :param sid: Fetch by unique recording Sid - - :returns: twilio.rest.api.v2010.account.recording.RecordingContext - :rtype: twilio.rest.api.v2010.account.recording.RecordingContext + Access the add_on_results """ - return RecordingContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.add_on_results - def __call__(self, sid): + @property + def transcriptions(self) -> TranscriptionList: """ - Constructs a RecordingContext - - :param sid: Fetch by unique recording Sid - - :returns: twilio.rest.api.v2010.account.recording.RecordingContext - :rtype: twilio.rest.api.v2010.account.recording.RecordingContext + Access the transcriptions """ - return RecordingContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.transcriptions - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class RecordingPage(Page): - """ """ +class RecordingContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str, sid: str): """ - Initialize the RecordingPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The unique sid that identifies this account + Initialize the RecordingContext - :returns: twilio.rest.api.v2010.account.recording.RecordingPage - :rtype: twilio.rest.api.v2010.account.recording.RecordingPage + :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(RecordingPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of RecordingInstance + Deletes the RecordingInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.api.v2010.account.recording.RecordingInstance - :rtype: twilio.rest.api.v2010.account.recording.RecordingInstance + :returns: True if delete succeeds, False otherwise """ - return RecordingInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the RecordingInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class RecordingContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, account_sid, sid): + def fetch( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> RecordingInstance: """ - Initialize the RecordingContext + Fetch the RecordingInstance - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param sid: Fetch by unique recording Sid + :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: twilio.rest.api.v2010.account.recording.RecordingContext - :rtype: twilio.rest.api.v2010.account.recording.RecordingContext + :returns: The fetched RecordingInstance """ - super(RecordingContext, self).__init__(version) - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/Recordings/{sid}.json'.format(**self._solution) + data = values.of( + { + "IncludeSoftDeleted": serialize.boolean_to_string(include_soft_deleted), + } + ) + + headers = values.of({}) - # Dependents - self._transcriptions = None - self._add_on_results = None + headers["Accept"] = "application/json" - def fetch(self): + 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: """ - Fetch a 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: Fetched RecordingInstance - :rtype: twilio.rest.api.v2010.account.recording.RecordingInstance + :returns: The fetched RecordingInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def delete(self): + @property + def add_on_results(self) -> AddOnResultList: """ - Deletes the RecordingInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool + Access the add_on_results """ - return self._version.delete('delete', self._uri) + 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): + def transcriptions(self) -> TranscriptionList: """ Access the transcriptions - - :returns: twilio.rest.api.v2010.account.recording.transcription.TranscriptionList - :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionList """ if self._transcriptions is None: self._transcriptions = TranscriptionList( self._version, - account_sid=self._solution['account_sid'], - recording_sid=self._solution['sid'], + self._solution["account_sid"], + self._solution["sid"], ) return self._transcriptions - @property - def add_on_results(self): + def __repr__(self) -> str: """ - Access the add_on_results + Provide a friendly representation - :returns: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultList - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultList + :returns: Machine friendly representation """ - if self._add_on_results is None: - self._add_on_results = AddOnResultList( - self._version, - account_sid=self._solution['account_sid'], - reference_sid=self._solution['sid'], - ) - return self._add_on_results + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - def __repr__(self): +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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" -class RecordingInstance(InstanceResource): - """ """ +class RecordingList(ListResource): - class Status(object): - IN_PROGRESS = "in-progress" - PAUSED = "paused" - STOPPED = "stopped" - PROCESSING = "processing" - COMPLETED = "completed" - FAILED = "failed" + def __init__(self, version: Version, account_sid: str): + """ + Initialize the RecordingList - class Source(object): - DIALVERB = "DialVerb" - CONFERENCE = "Conference" - OUTBOUNDAPI = "OutboundAPI" - TRUNKING = "Trunking" - RECORDVERB = "RecordVerb" - STARTCALLRECORDINGAPI = "StartCallRecordingAPI" - STARTCONFERENCERECORDINGAPI = "StartConferenceRecordingAPI" + :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) - def __init__(self, version, payload, account_sid, sid=None): - """ - Initialize the RecordingInstance - - :returns: twilio.rest.api.v2010.account.recording.RecordingInstance - :rtype: twilio.rest.api.v2010.account.recording.RecordingInstance - """ - super(RecordingInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'api_version': payload['api_version'], - 'call_sid': payload['call_sid'], - 'conference_sid': payload['conference_sid'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'duration': payload['duration'], - 'sid': payload['sid'], - 'price': payload['price'], - 'price_unit': payload['price_unit'], - 'status': payload['status'], - 'channels': deserialize.integer(payload['channels']), - 'source': payload['source'], - 'error_code': deserialize.integer(payload['error_code']), - 'uri': payload['uri'], - 'encryption_details': payload['encryption_details'], - 'subresource_uris': payload['subresource_uris'], + # 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. - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } + :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) - @property - def _proxy(self): + :returns: Generator that will yield up to limit results """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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"], + ) - :returns: RecordingContext for this RecordingInstance - :rtype: twilio.rest.api.v2010.account.recording.RecordingContext - """ - if self._context is None: - self._context = RecordingContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + 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. - @property - def account_sid(self): - """ - :returns: The unique sid that identifies this account - :rtype: unicode - """ - return self._properties['account_sid'] + :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) - @property - def api_version(self): - """ - :returns: The version of the API in use during the recording. - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['api_version'] + 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"], + ) - @property - def call_sid(self): - """ - :returns: The unique id for the call leg that corresponds to the recording. - :rtype: unicode - """ - return self._properties['call_sid'] + return self._version.stream_async(page, limits["limit"]) - @property - def conference_sid(self): + 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]: """ - :returns: The unique id for the conference associated with the recording, if a conference recording. - :rtype: unicode - """ - return self._properties['conference_sid'] + Lists RecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def date_created(self): - """ - :returns: The date this resource was created - :rtype: datetime - """ - return self._properties['date_created'] + :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, + ) + ) - @property - def date_updated(self): - """ - :returns: The date this resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + 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. - @property - def duration(self): - """ - :returns: The length of the recording, in seconds. - :rtype: unicode + :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: """ - return self._properties['duration'] + Retrieve a single page of RecordingInstance records from the API. + Request is executed immediately - @property - def sid(self): - """ - :returns: A string that uniquely identifies this recording - :rtype: unicode - """ - return self._properties['sid'] + :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 - @property - def price(self): - """ - :returns: The one-time cost of creating this recording. - :rtype: unicode + :returns: Page of RecordingInstance """ - return self._properties['price'] + 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, + } + ) - @property - def price_unit(self): - """ - :returns: The currency used in the Price property. - :rtype: unicode - """ - return self._properties['price_unit'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def status(self): - """ - :returns: The status of the recording. - :rtype: RecordingInstance.Status - """ - return self._properties['status'] + headers["Accept"] = "application/json" - @property - def channels(self): - """ - :returns: The number of channels in the final recording file as an integer. - :rtype: unicode - """ - return self._properties['channels'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordingPage(self._version, response, self._solution) - @property - def source(self): - """ - :returns: The way in which this recording was created. - :rtype: RecordingInstance.Source - """ - return self._properties['source'] + 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 - @property - def error_code(self): - """ - :returns: More information about the recording failure, if Status is failed. - :rtype: unicode - """ - return self._properties['error_code'] + :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 - @property - def uri(self): - """ - :returns: The URI for this resource - :rtype: unicode + :returns: Page of RecordingInstance """ - return self._properties['uri'] + 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, + } + ) - @property - def encryption_details(self): - """ - :returns: The encryption_details - :rtype: dict - """ - return self._properties['encryption_details'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def subresource_uris(self): - """ - :returns: The subresource_uris - :rtype: unicode - """ - return self._properties['subresource_uris'] + 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 fetch(self): + def get_page(self, target_url: str) -> RecordingPage: """ - Fetch a RecordingInstance + Retrieve a specific page of RecordingInstance records from the API. + Request is executed immediately - :returns: Fetched RecordingInstance - :rtype: twilio.rest.api.v2010.account.recording.RecordingInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of RecordingInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return RecordingPage(self._version, response, self._solution) - def delete(self): + async def get_page_async(self, target_url: str) -> RecordingPage: """ - Deletes the RecordingInstance + Asynchronously retrieve a specific page of RecordingInstance records from the API. + Request is executed immediately - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param target_url: API-generated URL for the requested results page + + :returns: Page of RecordingInstance """ - return self._proxy.delete() + response = await self._version.domain.twilio.request_async("GET", target_url) + return RecordingPage(self._version, response, self._solution) - @property - def transcriptions(self): + def get(self, sid: str) -> RecordingContext: """ - Access the transcriptions + Constructs a RecordingContext - :returns: twilio.rest.api.v2010.account.recording.transcription.TranscriptionList - :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionList + :param sid: The Twilio-provided string that uniquely identifies the Recording resource to fetch. """ - return self._proxy.transcriptions + return RecordingContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - @property - def add_on_results(self): + def __call__(self, sid: str) -> RecordingContext: """ - Access the add_on_results + Constructs a RecordingContext - :returns: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultList - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultList + :param sid: The Twilio-provided string that uniquely identifies the Recording resource to fetch. """ - return self._proxy.add_on_results + return RecordingContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 index 1fe05aa1ce..95296f3cc4 100644 --- a/twilio/rest/api/v2010/account/recording/add_on_result/__init__.py +++ b/twilio/rest/api/v2010/account/recording/add_on_result/__init__.py @@ -1,469 +1,553 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 AddOnResultList(ListResource): - """ """ - - def __init__(self, version, account_sid, reference_sid): - """ - Initialize the AddOnResultList +class AddOnResultInstance(InstanceResource): - :param Version version: Version that contains the resource - :param account_sid: The unique sid that identifies this account - :param reference_sid: A string that uniquely identifies the recording. + class Status(object): + CANCELED = "canceled" + COMPLETED = "completed" + DELETED = "deleted" + FAILED = "failed" + IN_PROGRESS = "in-progress" + INIT = "init" + PROCESSING = "processing" + QUEUED = "queued" - :returns: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultList - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultList - """ - super(AddOnResultList, self).__init__(version) + """ + :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" + ) - # 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) + self._solution = { + "account_sid": account_sid, + "reference_sid": reference_sid, + "sid": sid or self.sid, + } + self._context: Optional[AddOnResultContext] = None - def stream(self, limit=None, page_size=None): + @property + def _proxy(self) -> "AddOnResultContext": """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultInstance] + :returns: AddOnResultContext for this AddOnResultInstance """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) + 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 list(self, limit=None, page_size=None): + def delete(self) -> bool: """ - Lists AddOnResultInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the AddOnResultInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.delete() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def delete_async(self) -> bool: """ - Retrieve a single page of AddOnResultInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the AddOnResultInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of AddOnResultInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultPage + :returns: True if delete succeeds, False otherwise """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.delete_async() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return AddOnResultPage(self._version, response, self._solution) - - def get_page(self, target_url): + def fetch(self) -> "AddOnResultInstance": """ - Retrieve a specific page of AddOnResultInstance records from the API. - Request is executed immediately + Fetch the AddOnResultInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of AddOnResultInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultPage + :returns: The fetched AddOnResultInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return AddOnResultPage(self._version, response, self._solution) + return self._proxy.fetch() - def get(self, sid): + async def fetch_async(self) -> "AddOnResultInstance": """ - Constructs a AddOnResultContext + Asynchronous coroutine to fetch the AddOnResultInstance - :param sid: Fetch by unique result Sid - :returns: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultContext - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultContext + :returns: The fetched AddOnResultInstance """ - return AddOnResultContext( - self._version, - account_sid=self._solution['account_sid'], - reference_sid=self._solution['reference_sid'], - sid=sid, - ) + return await self._proxy.fetch_async() - def __call__(self, sid): + @property + def payloads(self) -> PayloadList: """ - Constructs a AddOnResultContext - - :param sid: Fetch by unique result Sid - - :returns: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultContext - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultContext + Access the payloads """ - return AddOnResultContext( - self._version, - account_sid=self._solution['account_sid'], - reference_sid=self._solution['reference_sid'], - sid=sid, - ) + return self._proxy.payloads - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class AddOnResultPage(Page): - """ """ +class AddOnResultContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__( + self, version: Version, account_sid: str, reference_sid: str, sid: str + ): """ - Initialize the AddOnResultPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The unique sid that identifies this account - :param reference_sid: A string that uniquely identifies the recording. + Initialize the AddOnResultContext - :returns: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultPage - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultPage + :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(AddOnResultPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of AddOnResultInstance + 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 + ) - :param dict payload: Payload response from the API + self._payloads: Optional[PayloadList] = None - :returns: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultInstance + def delete(self) -> bool: """ - return AddOnResultInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - reference_sid=self._solution['reference_sid'], - ) + Deletes the AddOnResultInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class AddOnResultContext(InstanceContext): - """ """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, account_sid, reference_sid, sid): + async def delete_async(self) -> bool: """ - Initialize the AddOnResultContext + Asynchronous coroutine that deletes the AddOnResultInstance - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param reference_sid: The reference_sid - :param sid: Fetch by unique result Sid - :returns: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultContext - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultContext + :returns: True if delete succeeds, False otherwise """ - super(AddOnResultContext, self).__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) + headers = values.of({}) - # Dependents - self._payloads = None + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> AddOnResultInstance: """ - Fetch a AddOnResultInstance + Fetch the AddOnResultInstance - :returns: Fetched AddOnResultInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultInstance + + :returns: The fetched AddOnResultInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) + 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'], + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def fetch_async(self) -> AddOnResultInstance: """ - Deletes the AddOnResultInstance + Asynchronous coroutine to fetch the AddOnResultInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: The fetched AddOnResultInstance """ - return self._version.delete('delete', self._uri) + + 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): + def payloads(self) -> PayloadList: """ Access the payloads - - :returns: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadList - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadList """ if self._payloads is None: self._payloads = PayloadList( self._version, - account_sid=self._solution['account_sid'], - reference_sid=self._solution['reference_sid'], - add_on_result_sid=self._solution['sid'], + self._solution["account_sid"], + self._solution["reference_sid"], + self._solution["sid"], ) return self._payloads - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class AddOnResultInstance(InstanceResource): - """ """ +class AddOnResultPage(Page): - class Status(object): - CANCELED = "canceled" - COMPLETED = "completed" - DELETED = "deleted" - FAILED = "failed" - IN_PROGRESS = "in-progress" - INIT = "init" - PROCESSING = "processing" - QUEUED = "queued" + def get_instance(self, payload: Dict[str, Any]) -> AddOnResultInstance: + """ + Build an instance of AddOnResultInstance - def __init__(self, version, payload, account_sid, reference_sid, sid=None): + :param payload: Payload response from the API """ - Initialize the AddOnResultInstance + return AddOnResultInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + ) - :returns: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultInstance + def __repr__(self) -> str: """ - super(AddOnResultInstance, self).__init__(version) + Provide a friendly representation - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'status': payload['status'], - 'add_on_sid': payload['add_on_sid'], - 'add_on_configuration_sid': payload['add_on_configuration_sid'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'date_completed': deserialize.rfc2822_datetime(payload['date_completed']), - 'reference_sid': payload['reference_sid'], - 'subresource_uris': payload['subresource_uris'], - } + :returns: Machine friendly representation + """ + return "" - # Context - self._context = None - self._solution = { - 'account_sid': account_sid, - 'reference_sid': reference_sid, - 'sid': sid or self._properties['sid'], - } - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context +class AddOnResultList(ListResource): - :returns: AddOnResultContext for this AddOnResultInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultContext + def __init__(self, version: Version, account_sid: str, reference_sid: str): """ - 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 + Initialize the AddOnResultList - @property - def sid(self): - """ - :returns: A string that uniquely identifies this result - :rtype: unicode - """ - return self._properties['sid'] + :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. - @property - def account_sid(self): """ - :returns: The unique sid that identifies this account - :rtype: unicode - """ - return self._properties['account_sid'] + super().__init__(version) - @property - def status(self): - """ - :returns: The status of this result. - :rtype: AddOnResultInstance.Status - """ - return self._properties['status'] + # 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 + ) - @property - def add_on_sid(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AddOnResultInstance]: """ - :returns: A string that uniquely identifies the Add-on. - :rtype: unicode + 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 """ - return self._properties['add_on_sid'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def add_on_configuration_sid(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AddOnResultInstance]: """ - :returns: A string that uniquely identifies the Add-on configuration. - :rtype: unicode + 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 """ - return self._properties['add_on_configuration_sid'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def date_created(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AddOnResultInstance]: """ - :returns: The date this resource was created - :rtype: datetime + 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 self._properties['date_created'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def date_updated(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AddOnResultInstance]: """ - :returns: The date this resource was last updated - :rtype: datetime + 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 self._properties['date_updated'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def date_completed(self): + 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: """ - :returns: The date this result was completed. - :rtype: datetime + 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 """ - return self._properties['date_completed'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def reference_sid(self): + headers = values.of({"Content-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: """ - :returns: A string that uniquely identifies the recording. - :rtype: unicode + 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 """ - return self._properties['reference_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def subresource_uris(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The subresource_uris - :rtype: unicode + 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 """ - return self._properties['subresource_uris'] + response = self._version.domain.twilio.request("GET", target_url) + return AddOnResultPage(self._version, response, self._solution) - def fetch(self): + async def get_page_async(self, target_url: str) -> AddOnResultPage: """ - Fetch a AddOnResultInstance + 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: Fetched AddOnResultInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultInstance + :returns: Page of AddOnResultInstance """ - return self._proxy.fetch() + response = await self._version.domain.twilio.request_async("GET", target_url) + return AddOnResultPage(self._version, response, self._solution) - def delete(self): + def get(self, sid: str) -> AddOnResultContext: """ - Deletes the AddOnResultInstance + Constructs a AddOnResultContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the Recording AddOnResult resource to fetch. """ - return self._proxy.delete() + return AddOnResultContext( + self._version, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + sid=sid, + ) - @property - def payloads(self): + def __call__(self, sid: str) -> AddOnResultContext: """ - Access the payloads + Constructs a AddOnResultContext - :returns: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadList - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadList + :param sid: The Twilio-provided string that uniquely identifies the Recording AddOnResult resource to fetch. """ - return self._proxy.payloads + return AddOnResultContext( + self._version, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 index 92dd4bf306..08e6ea2109 100644 --- 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 @@ -1,456 +1,566 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 PayloadList(ListResource): - """ """ +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" + ) - def __init__(self, version, account_sid, reference_sid, add_on_result_sid): + 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": """ - Initialize the PayloadList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param account_sid: The unique sid that identifies this account - :param reference_sid: A string that uniquely identifies the recording. - :param add_on_result_sid: A string that uniquely identifies the result + :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 - :returns: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadList - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadList + def delete(self) -> bool: """ - super(PayloadList, self).__init__(version) + Deletes the PayloadInstance - # 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=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PayloadInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadInstance] + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() + + def fetch(self) -> "PayloadInstance": + """ + Fetch the PayloadInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched PayloadInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the PayloadInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadInstance] + :returns: The fetched PayloadInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + @property + def data(self) -> DataList: """ - Retrieve a single page of PayloadInstance records from the API. - Request is executed immediately + Access the data + """ + return self._proxy.data - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of PayloadInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadPage + :returns: Machine friendly representation """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - response = self._version.page( - 'GET', - self._uri, - params=params, + +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 ) - return PayloadPage(self._version, response, self._solution) + self._data: Optional[DataList] = None - def get_page(self, target_url): + def delete(self) -> bool: """ - Retrieve a specific page of PayloadInstance records from the API. - Request is executed immediately + Deletes the PayloadInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of PayloadInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadPage + :returns: True if delete succeeds, False otherwise """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return PayloadPage(self._version, response, self._solution) + headers = values.of({}) - def get(self, sid): + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Constructs a PayloadContext + Asynchronous coroutine that deletes the PayloadInstance - :param sid: Fetch by unique payload Sid - :returns: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadContext - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadContext + :returns: True if delete succeeds, False otherwise """ - 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, + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers ) - def __call__(self, sid): + def fetch(self) -> PayloadInstance: """ - Constructs a PayloadContext + Fetch the PayloadInstance - :param sid: Fetch by unique payload Sid - :returns: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadContext - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadContext + :returns: The fetched PayloadInstance """ - return PayloadContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return PayloadInstance( 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, + 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"], ) - def __repr__(self): + async def fetch_async(self) -> PayloadInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the PayloadInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched PayloadInstance """ - return '' + headers = values.of({}) -class PayloadPage(Page): - """ """ + 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"], + ) - def __init__(self, version, response, solution): + @property + def data(self) -> DataList: + """ + Access the data """ - Initialize the PayloadPage + 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 - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The unique sid that identifies this account - :param reference_sid: A string that uniquely identifies the recording. - :param add_on_result_sid: A string that uniquely identifies the result + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadPage - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadPage + :returns: Machine friendly representation """ - super(PayloadPage, self).__init__(version, response) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Path Solution - self._solution = solution - def get_instance(self, payload): +class PayloadPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PayloadInstance: """ Build an instance of PayloadInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.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'], + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class PayloadContext(InstanceContext): - """ """ +class PayloadList(ListResource): - def __init__(self, version, account_sid, reference_sid, add_on_result_sid, sid): + def __init__( + self, + version: Version, + account_sid: str, + reference_sid: str, + add_on_result_sid: str, + ): """ - Initialize the PayloadContext + Initialize the PayloadList - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param reference_sid: The reference_sid - :param add_on_result_sid: The add_on_result_sid - :param sid: Fetch by unique payload Sid + :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. - :returns: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadContext - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadContext """ - super(PayloadContext, self).__init__(version) + 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, + "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/{sid}.json'.format(**self._solution) + self._uri = "/Accounts/{account_sid}/Recordings/{reference_sid}/AddOnResults/{add_on_result_sid}/Payloads.json".format( + **self._solution + ) - def fetch(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PayloadInstance]: """ - Fetch a 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. - :returns: Fetched PayloadInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadInstance - """ - params = values.of({}) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) + :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 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'], - ) + return self._version.stream(page, limits["limit"]) - def delete(self): + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PayloadInstance]: """ - Deletes the 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. - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - def __repr__(self): + :returns: Generator that will yield up to limit results """ - Provide a friendly representation + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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. -class PayloadInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid, reference_sid, - add_on_result_sid, sid=None): - """ - Initialize the PayloadInstance - - :returns: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadInstance - """ - super(PayloadInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'add_on_result_sid': payload['add_on_result_sid'], - 'account_sid': payload['account_sid'], - 'label': payload['label'], - 'add_on_sid': payload['add_on_sid'], - 'add_on_configuration_sid': payload['add_on_configuration_sid'], - 'content_type': payload['content_type'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'reference_sid': payload['reference_sid'], - 'subresource_uris': payload['subresource_uris'], - } + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - # Context - self._context = None - self._solution = { - 'account_sid': account_sid, - 'reference_sid': reference_sid, - 'add_on_result_sid': add_on_result_sid, - 'sid': sid or self._properties['sid'], - } + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def _proxy(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PayloadInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: PayloadContext for this PayloadInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadContext + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - 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 [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, ) - return self._context + ] - @property - def sid(self): - """ - :returns: A string that uniquely identifies this payload - :rtype: unicode + 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: """ - return self._properties['sid'] + Retrieve a single page of PayloadInstance records from the API. + Request is executed immediately - @property - def add_on_result_sid(self): - """ - :returns: A string that uniquely identifies the result - :rtype: unicode - """ - return self._properties['add_on_result_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 - @property - def account_sid(self): - """ - :returns: The unique sid that identifies this account - :rtype: unicode + :returns: Page of PayloadInstance """ - return self._properties['account_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def label(self): - """ - :returns: A string that describes the payload. - :rtype: unicode - """ - return self._properties['label'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def add_on_sid(self): - """ - :returns: A string that uniquely identifies the Add-on. - :rtype: unicode - """ - return self._properties['add_on_sid'] + headers["Accept"] = "application/json" - @property - def add_on_configuration_sid(self): - """ - :returns: A string that uniquely identifies the Add-on configuration. - :rtype: unicode - """ - return self._properties['add_on_configuration_sid'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PayloadPage(self._version, response, self._solution) - @property - def content_type(self): - """ - :returns: The MIME type of the payload. - :rtype: unicode + 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: """ - return self._properties['content_type'] + Asynchronously retrieve a single page of PayloadInstance records from the API. + Request is executed immediately - @property - def date_created(self): - """ - :returns: The date this resource was created - :rtype: datetime - """ - return self._properties['date_created'] + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - @property - def date_updated(self): - """ - :returns: The date this resource was last updated - :rtype: datetime + :returns: Page of PayloadInstance """ - return self._properties['date_updated'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def reference_sid(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: A string that uniquely identifies the recording. - :rtype: unicode + 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 """ - return self._properties['reference_sid'] + response = self._version.domain.twilio.request("GET", target_url) + return PayloadPage(self._version, response, self._solution) - @property - def subresource_uris(self): + async def get_page_async(self, target_url: str) -> PayloadPage: """ - :returns: The subresource_uris - :rtype: unicode + 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 """ - return self._properties['subresource_uris'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return PayloadPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> PayloadContext: """ - Fetch a PayloadInstance + Constructs a PayloadContext - :returns: Fetched PayloadInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadInstance + :param sid: The Twilio-provided string that uniquely identifies the Recording AddOnResult Payload resource to fetch. """ - return self._proxy.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 delete(self): + def __call__(self, sid: str) -> PayloadContext: """ - Deletes the PayloadInstance + Constructs a PayloadContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the Recording AddOnResult Payload resource to fetch. """ - return self._proxy.delete() + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 "".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 "".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 "" diff --git a/twilio/rest/api/v2010/account/recording/transcription.py b/twilio/rest/api/v2010/account/recording/transcription.py index 8fc27dd6e0..472f5b2bff 100644 --- a/twilio/rest/api/v2010/account/recording/transcription.py +++ b/twilio/rest/api/v2010/account/recording/transcription.py @@ -1,460 +1,524 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 TranscriptionList(ListResource): - """ """ - - def __init__(self, version, account_sid, recording_sid): - """ - Initialize the TranscriptionList +class TranscriptionInstance(InstanceResource): - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param recording_sid: The recording_sid + class Status(object): + IN_PROGRESS = "in-progress" + COMPLETED = "completed" + FAILED = "failed" - :returns: twilio.rest.api.v2010.account.recording.transcription.TranscriptionList - :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionList - """ - super(TranscriptionList, self).__init__(version) + """ + :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") - # 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) + self._solution = { + "account_sid": account_sid, + "recording_sid": recording_sid, + "sid": sid or self.sid, + } + self._context: Optional[TranscriptionContext] = None - def stream(self, limit=None, page_size=None): + @property + def _proxy(self) -> "TranscriptionContext": """ - 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. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the TranscriptionInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists TranscriptionInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the TranscriptionInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "TranscriptionInstance": """ - Retrieve a single page of TranscriptionInstance records from the API. - Request is executed immediately + Fetch the TranscriptionInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionPage + :returns: The fetched TranscriptionInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + async def fetch_async(self) -> "TranscriptionInstance": + """ + Asynchronous coroutine to fetch the TranscriptionInstance - return TranscriptionPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched TranscriptionInstance """ - Retrieve a specific page of TranscriptionInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_async() - :param str target_url: API-generated URL for the requested results page + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionPage + :returns: Machine friendly representation """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - return TranscriptionPage(self._version, response, self._solution) - def get(self, sid): - """ - Constructs a TranscriptionContext +class TranscriptionContext(InstanceContext): - :param sid: The sid + def __init__( + self, version: Version, account_sid: str, recording_sid: str, sid: str + ): + """ + Initialize the TranscriptionContext - :returns: twilio.rest.api.v2010.account.recording.transcription.TranscriptionContext - :rtype: twilio.rest.api.v2010.account.recording.transcription.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. """ - return TranscriptionContext( - self._version, - account_sid=self._solution['account_sid'], - recording_sid=self._solution['recording_sid'], - sid=sid, + 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 __call__(self, sid): + def delete(self) -> bool: """ - Constructs a TranscriptionContext + Deletes the TranscriptionInstance - :param sid: The sid - :returns: twilio.rest.api.v2010.account.recording.transcription.TranscriptionContext - :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionContext + :returns: True if delete succeeds, False otherwise """ - return TranscriptionContext( - self._version, - account_sid=self._solution['account_sid'], - recording_sid=self._solution['recording_sid'], - sid=sid, - ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the TranscriptionInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class TranscriptionPage(Page): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> TranscriptionInstance: """ - Initialize the TranscriptionPage + Fetch the TranscriptionInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The account_sid - :param recording_sid: The recording_sid - :returns: twilio.rest.api.v2010.account.recording.transcription.TranscriptionPage - :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionPage + :returns: The fetched TranscriptionInstance """ - super(TranscriptionPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): - """ - Build an instance of TranscriptionInstance + headers["Accept"] = "application/json" - :param dict payload: Payload response from the API + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance - """ return TranscriptionInstance( self._version, payload, - account_sid=self._solution['account_sid'], - recording_sid=self._solution['recording_sid'], + account_sid=self._solution["account_sid"], + recording_sid=self._solution["recording_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + async def fetch_async(self) -> TranscriptionInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the TranscriptionInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched TranscriptionInstance """ - return '' + headers = values.of({}) -class TranscriptionContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, account_sid, recording_sid, sid): - """ - Initialize the TranscriptionContext + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param recording_sid: The recording_sid - :param sid: The sid + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + recording_sid=self._solution["recording_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.api.v2010.account.recording.transcription.TranscriptionContext - :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionContext + def __repr__(self) -> str: """ - super(TranscriptionContext, self).__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) + Provide a friendly representation - def fetch(self): + :returns: Machine friendly representation """ - Fetch a TranscriptionInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: Fetched TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance - """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) +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'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + recording_sid=self._solution["recording_sid"], ) - def delete(self): - """ - Deletes the TranscriptionInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" -class TranscriptionInstance(InstanceResource): - """ """ +class TranscriptionList(ListResource): - class Status(object): - IN_PROGRESS = "in-progress" - COMPLETED = "completed" - FAILED = "failed" + def __init__(self, version: Version, account_sid: str, recording_sid: str): + """ + Initialize the TranscriptionList - def __init__(self, version, payload, account_sid, recording_sid, sid=None): - """ - Initialize the TranscriptionInstance - - :returns: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance - """ - super(TranscriptionInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'api_version': payload['api_version'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'duration': payload['duration'], - 'price': deserialize.decimal(payload['price']), - 'price_unit': payload['price_unit'], - 'recording_sid': payload['recording_sid'], - 'sid': payload['sid'], - 'status': payload['status'], - 'transcription_text': payload['transcription_text'], - 'type': payload['type'], - 'uri': payload['uri'], - } + :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) - # Context - self._context = None + # Path Solution self._solution = { - 'account_sid': account_sid, - 'recording_sid': recording_sid, - 'sid': sid or self._properties['sid'], + "account_sid": account_sid, + "recording_sid": recording_sid, } + self._uri = "/Accounts/{account_sid}/Recordings/{recording_sid}/Transcriptions.json".format( + **self._solution + ) - @property - def _proxy(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TranscriptionInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: TranscriptionContext for this TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionContext - """ - 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 + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['account_sid'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def api_version(self): - """ - :returns: The api_version - :rtype: unicode - """ - return self._properties['api_version'] + return self._version.stream(page, limits["limit"]) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TranscriptionInstance]: """ - return self._properties['date_created'] + 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. - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - @property - def duration(self): - """ - :returns: The duration - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['duration'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def price(self): - """ - :returns: The price - :rtype: unicode - """ - return self._properties['price'] + return self._version.stream_async(page, limits["limit"]) - @property - def price_unit(self): - """ - :returns: The price_unit - :rtype: unicode + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TranscriptionInstance]: """ - return self._properties['price_unit'] + Lists TranscriptionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def recording_sid(self): - """ - :returns: The recording_sid - :rtype: unicode + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['recording_sid'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TranscriptionInstance]: """ - :returns: The sid - :rtype: unicode + 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 self._properties['sid'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def status(self): + 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: """ - :returns: The status - :rtype: TranscriptionInstance.Status + 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 """ - return self._properties['status'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def transcription_text(self): + headers = values.of({"Content-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: """ - :returns: The transcription_text - :rtype: unicode + 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 """ - return self._properties['transcription_text'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def type(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The type - :rtype: unicode + 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 """ - return self._properties['type'] + response = self._version.domain.twilio.request("GET", target_url) + return TranscriptionPage(self._version, response, self._solution) - @property - def uri(self): + async def get_page_async(self, target_url: str) -> TranscriptionPage: """ - :returns: The uri - :rtype: unicode + 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 """ - return self._properties['uri'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return TranscriptionPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> TranscriptionContext: """ - Fetch a TranscriptionInstance + Constructs a TranscriptionContext - :returns: Fetched TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance + :param sid: The Twilio-provided string that uniquely identifies the Transcription resource to fetch. """ - return self._proxy.fetch() + return TranscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + recording_sid=self._solution["recording_sid"], + sid=sid, + ) - def delete(self): + def __call__(self, sid: str) -> TranscriptionContext: """ - Deletes the TranscriptionInstance + Constructs a TranscriptionContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the Transcription resource to fetch. """ - return self._proxy.delete() + return TranscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + recording_sid=self._solution["recording_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/api/v2010/account/short_code.py b/twilio/rest/api/v2010/account/short_code.py index fcc605d9a2..eae35c4aa5 100644 --- a/twilio/rest/api/v2010/account/short_code.py +++ b/twilio/rest/api/v2010/account/short_code.py @@ -1,487 +1,650 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 ShortCodeList(ListResource): - """ """ +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 - def __init__(self, version, account_sid): + @property + def _proxy(self) -> "ShortCodeContext": """ - Initialize the ShortCodeList - - :param Version version: Version that contains the resource - :param account_sid: The unique sid that identifies this account + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: twilio.rest.api.v2010.account.short_code.ShortCodeList - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeList + :returns: ShortCodeContext for this ShortCodeInstance """ - super(ShortCodeList, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/SMS/ShortCodes.json'.format(**self._solution) + if self._context is None: + self._context = ShortCodeContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - def stream(self, friendly_name=values.unset, short_code=values.unset, - limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the ShortCodeInstance - :param unicode friendly_name: Filter by friendly name - :param unicode short_code: Filter by ShortCode - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.short_code.ShortCodeInstance] + :returns: The fetched ShortCodeInstance """ - 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'], limits['page_limit']) + return self._proxy.fetch() - def list(self, friendly_name=values.unset, short_code=values.unset, limit=None, - page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the ShortCodeInstance - :param unicode friendly_name: Filter by friendly name - :param unicode short_code: Filter by ShortCode - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.short_code.ShortCodeInstance] + :returns: The fetched ShortCodeInstance """ - return list(self.stream( - friendly_name=friendly_name, - short_code=short_code, - limit=limit, - page_size=page_size, - )) + return await self._proxy.fetch_async() - def page(self, friendly_name=values.unset, short_code=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + 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": """ - Retrieve a single page of ShortCodeInstance records from the API. - Request is executed immediately + Update the ShortCodeInstance - :param unicode friendly_name: Filter by friendly name - :param unicode short_code: Filter by ShortCode - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :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: Page of ShortCodeInstance - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodePage + :returns: The updated ShortCodeInstance """ - params = values.of({ - 'FriendlyName': friendly_name, - 'ShortCode': short_code, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + 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, ) - return ShortCodePage(self._version, response, self._solution) - - def get_page(self, target_url): + 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": """ - Retrieve a specific page of ShortCodeInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the ShortCodeInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of ShortCodeInstance - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodePage + :returns: The updated ShortCodeInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, ) - return ShortCodePage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a ShortCodeContext - - :param sid: Fetch by unique short-code Sid - - :returns: twilio.rest.api.v2010.account.short_code.ShortCodeContext - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeContext - """ - return ShortCodeContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a ShortCodeContext - - :param sid: Fetch by unique short-code Sid - - :returns: twilio.rest.api.v2010.account.short_code.ShortCodeContext - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeContext - """ - return ShortCodeContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) - - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ShortCodePage(Page): - """ """ +class ShortCodeContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str, sid: str): """ - Initialize the ShortCodePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The unique sid that identifies this account + Initialize the ShortCodeContext - :returns: twilio.rest.api.v2010.account.short_code.ShortCodePage - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodePage + :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(ShortCodePage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SMS/ShortCodes/{sid}.json".format( + **self._solution + ) - def get_instance(self, payload): + def fetch(self) -> ShortCodeInstance: """ - Build an instance of ShortCodeInstance + Fetch the ShortCodeInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.api.v2010.account.short_code.ShortCodeInstance - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeInstance + :returns: The fetched ShortCodeInstance """ - return ShortCodeInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - def __repr__(self): - """ - Provide a friendly representation + headers = values.of({}) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Accept"] = "application/json" + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) -class ShortCodeContext(InstanceContext): - """ """ + return ShortCodeInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - def __init__(self, version, account_sid, sid): + async def fetch_async(self) -> ShortCodeInstance: """ - Initialize the ShortCodeContext + Asynchronous coroutine to fetch the ShortCodeInstance - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param sid: Fetch by unique short-code Sid - :returns: twilio.rest.api.v2010.account.short_code.ShortCodeContext - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeContext + :returns: The fetched ShortCodeInstance """ - super(ShortCodeContext, self).__init__(version) - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/SMS/ShortCodes/{sid}.json'.format(**self._solution) + headers = values.of({}) - def fetch(self): - """ - Fetch a ShortCodeInstance + headers["Accept"] = "application/json" - :returns: Fetched ShortCodeInstance - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def update(self, friendly_name=values.unset, api_version=values.unset, - sms_url=values.unset, sms_method=values.unset, - sms_fallback_url=values.unset, sms_fallback_method=values.unset): + 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 unicode friendly_name: A human readable description of this resource - :param unicode api_version: The API version to use - :param unicode sms_url: URL Twilio will request when receiving an SMS - :param unicode sms_method: HTTP method to use when requesting the sms url - :param unicode sms_fallback_url: URL Twilio will request if an error occurs in executing TwiML - :param unicode sms_fallback_method: HTTP method Twilio will use with sms fallback url - - :returns: Updated ShortCodeInstance - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'ApiVersion': api_version, - 'SmsUrl': sms_url, - 'SmsMethod': sms_method, - 'SmsFallbackUrl': sms_fallback_url, - 'SmsFallbackMethod': sms_fallback_method, - }) + :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( - 'POST', - self._uri, - data=data, + 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'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ShortCodeInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid, sid=None): - """ - Initialize the ShortCodeInstance - - :returns: twilio.rest.api.v2010.account.short_code.ShortCodeInstance - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeInstance - """ - super(ShortCodeInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'api_version': payload['api_version'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'friendly_name': payload['friendly_name'], - 'short_code': payload['short_code'], - 'sid': payload['sid'], - 'sms_fallback_method': payload['sms_fallback_method'], - 'sms_fallback_url': payload['sms_fallback_url'], - 'sms_method': payload['sms_method'], - 'sms_url': payload['sms_url'], - 'uri': payload['uri'], - } - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } +class ShortCodePage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> ShortCodeInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of ShortCodeInstance - :returns: ShortCodeContext for this ShortCodeInstance - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = ShortCodeContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + return ShortCodeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def account_sid(self): - """ - :returns: The unique sid that identifies this account - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def api_version(self): - """ - :returns: The API version to use - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['api_version'] + return "" - @property - def date_created(self): - """ - :returns: The date this resource was created - :rtype: datetime - """ - return self._properties['date_created'] - @property - def date_updated(self): - """ - :returns: The date this resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] +class ShortCodeList(ListResource): - @property - def friendly_name(self): - """ - :returns: A human readable description of this resource - :rtype: unicode + def __init__(self, version: Version, account_sid: str): """ - return self._properties['friendly_name'] + 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. - @property - def short_code(self): """ - :returns: The short code. e.g., 894546. - :rtype: unicode + 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]: """ - return self._properties['short_code'] + 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. - @property - def sid(self): + :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 """ - :returns: A string that uniquely identifies this short-codes - :rtype: unicode + 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]: """ - return self._properties['sid'] + 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. - @property - def sms_fallback_method(self): + :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 """ - :returns: HTTP method Twilio will use with sms fallback url - :rtype: unicode + 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]: """ - return self._properties['sms_fallback_method'] + Lists ShortCodeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def sms_fallback_url(self): + :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]: """ - :returns: URL Twilio will request if an error occurs in executing TwiML - :rtype: unicode + 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: """ - return self._properties['sms_fallback_url'] + Retrieve a single page of ShortCodeInstance records from the API. + Request is executed immediately - @property - def sms_method(self): + :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 """ - :returns: HTTP method to use when requesting the sms url - :rtype: unicode + 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: """ - return self._properties['sms_method'] + Asynchronously retrieve a single page of ShortCodeInstance records from the API. + Request is executed immediately - @property - def sms_url(self): + :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 """ - :returns: URL Twilio will request when receiving an SMS - :rtype: unicode + 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: """ - return self._properties['sms_url'] + Retrieve a specific page of ShortCodeInstance records from the API. + Request is executed immediately - @property - def uri(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of ShortCodeInstance """ - :returns: The URI for this resource - :rtype: unicode + 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: """ - return self._properties['uri'] + 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 - def fetch(self): + :returns: Page of ShortCodeInstance """ - Fetch a ShortCodeInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return ShortCodePage(self._version, response, self._solution) - :returns: Fetched ShortCodeInstance - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeInstance + def get(self, sid: str) -> ShortCodeContext: """ - return self._proxy.fetch() + Constructs a ShortCodeContext - def update(self, friendly_name=values.unset, api_version=values.unset, - sms_url=values.unset, sms_method=values.unset, - sms_fallback_url=values.unset, sms_fallback_method=values.unset): + :param sid: The Twilio-provided string that uniquely identifies the ShortCode resource to update """ - Update the ShortCodeInstance + return ShortCodeContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - :param unicode friendly_name: A human readable description of this resource - :param unicode api_version: The API version to use - :param unicode sms_url: URL Twilio will request when receiving an SMS - :param unicode sms_method: HTTP method to use when requesting the sms url - :param unicode sms_fallback_url: URL Twilio will request if an error occurs in executing TwiML - :param unicode sms_fallback_method: HTTP method Twilio will use with sms fallback url + def __call__(self, sid: str) -> ShortCodeContext: + """ + Constructs a ShortCodeContext - :returns: Updated ShortCodeInstance - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeInstance + :param sid: The Twilio-provided string that uniquely identifies the ShortCode resource to update """ - 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, + return ShortCodeContext( + self._version, account_sid=self._solution["account_sid"], sid=sid ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/api/v2010/account/signing_key.py b/twilio/rest/api/v2010/account/signing_key.py index 03d1cc3f9d..8e33f218f5 100644 --- a/twilio/rest/api/v2010/account/signing_key.py +++ b/twilio/rest/api/v2010/account/signing_key.py @@ -1,385 +1,572 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 SigningKeyList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the SigningKeyList +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") + ) - :param Version version: Version that contains the resource - :param account_sid: A 34 character string that uniquely identifies this resource. + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[SigningKeyContext] = None - :returns: twilio.rest.api.v2010.account.signing_key.SigningKeyList - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyList + @property + def _proxy(self) -> "SigningKeyContext": """ - super(SigningKeyList, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/SigningKeys.json'.format(**self._solution) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def stream(self, limit=None, page_size=None): + :returns: SigningKeyContext for this 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + if self._context is None: + self._context = SigningKeyContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.signing_key.SigningKeyInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the SigningKeyInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists SigningKeyInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the SigningKeyInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.signing_key.SigningKeyInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "SigningKeyInstance": """ - Retrieve a single page of SigningKeyInstance records from the API. - Request is executed immediately + Fetch the SigningKeyInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of SigningKeyInstance - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyPage + :returns: The fetched SigningKeyInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return SigningKeyPage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "SigningKeyInstance": """ - Retrieve a specific page of SigningKeyInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the SigningKeyInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of SigningKeyInstance - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyPage + :returns: The fetched SigningKeyInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return SigningKeyPage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def get(self, sid): + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> "SigningKeyInstance": """ - Constructs a SigningKeyContext + Update the SigningKeyInstance - :param sid: The sid + :param friendly_name: - :returns: twilio.rest.api.v2010.account.signing_key.SigningKeyContext - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyContext + :returns: The updated SigningKeyInstance """ - return SigningKeyContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.update( + friendly_name=friendly_name, + ) - def __call__(self, sid): + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "SigningKeyInstance": """ - Constructs a SigningKeyContext + Asynchronous coroutine to update the SigningKeyInstance - :param sid: The sid + :param friendly_name: - :returns: twilio.rest.api.v2010.account.signing_key.SigningKeyContext - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyContext + :returns: The updated SigningKeyInstance """ - return SigningKeyContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return await self._proxy.update_async( + friendly_name=friendly_name, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class SigningKeyPage(Page): - """ """ +class SigningKeyContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str, sid: str): """ - Initialize the SigningKeyPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: A 34 character string that uniquely identifies this resource. + Initialize the SigningKeyContext - :returns: twilio.rest.api.v2010.account.signing_key.SigningKeyPage - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyPage + :param version: Version that contains the resource + :param account_sid: + :param sid: """ - super(SigningKeyPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SigningKeys/{sid}.json".format( + **self._solution + ) - def get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of SigningKeyInstance + Deletes the SigningKeyInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.api.v2010.account.signing_key.SigningKeyInstance - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyInstance + :returns: True if delete succeeds, False otherwise """ - return SigningKeyInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the SigningKeyInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class SigningKeyContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, account_sid, sid): + def fetch(self) -> SigningKeyInstance: """ - Initialize the SigningKeyContext + Fetch the SigningKeyInstance - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param sid: The sid - :returns: twilio.rest.api.v2010.account.signing_key.SigningKeyContext - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyContext + :returns: The fetched SigningKeyInstance """ - super(SigningKeyContext, self).__init__(version) - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/SigningKeys/{sid}.json'.format(**self._solution) + 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"], + ) - def fetch(self): + async def fetch_async(self) -> SigningKeyInstance: """ - Fetch a SigningKeyInstance + Asynchronous coroutine to fetch the SigningKeyInstance + - :returns: Fetched SigningKeyInstance - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyInstance + :returns: The fetched SigningKeyInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def update(self, friendly_name=values.unset): + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> SigningKeyInstance: """ Update the SigningKeyInstance - :param unicode friendly_name: The friendly_name + :param friendly_name: - :returns: Updated SigningKeyInstance - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyInstance + :returns: The updated SigningKeyInstance """ - data = values.of({'FriendlyName': friendly_name, }) + + 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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) return SigningKeyInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> SigningKeyInstance: """ - Deletes the SigningKeyInstance + Asynchronous coroutine to update the SigningKeyInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param friendly_name: + + :returns: The updated SigningKeyInstance """ - return self._version.delete('delete', self._uri) - def __repr__(self): + 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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class SigningKeyInstance(InstanceResource): - """ """ +class SigningKeyPage(Page): - def __init__(self, version, payload, account_sid, sid=None): + def get_instance(self, payload: Dict[str, Any]) -> SigningKeyInstance: """ - Initialize the 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 "" + + +class SigningKeyList(ListResource): - :returns: twilio.rest.api.v2010.account.signing_key.SigningKeyInstance - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyInstance + def __init__(self, version: Version, account_sid: str): """ - super(SigningKeyInstance, self).__init__(version) + Initialize the SigningKeyList - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'friendly_name': payload['friendly_name'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), + :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) - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } + 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. - @property - def _proxy(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - :returns: SigningKeyContext for this SigningKeyInstance - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyContext + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SigningKeyInstance]: """ - if self._context is None: - self._context = SigningKeyContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + 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. - @property - def sid(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The sid - :rtype: unicode + 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]: """ - return self._properties['sid'] + Lists SigningKeyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def friendly_name(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + 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]: """ - :returns: The friendly_name - :rtype: unicode + 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 self._properties['friendly_name'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def date_created(self): + 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 """ - :returns: The date_created - :rtype: datetime + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['date_created'] + Asynchronously retrieve a single page of SigningKeyInstance records from the API. + Request is executed immediately - @property - def date_updated(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The date_updated - :rtype: datetime + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['date_updated'] + 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 - def fetch(self): + :returns: Page of SigningKeyInstance """ - Fetch a SigningKeyInstance + response = self._version.domain.twilio.request("GET", target_url) + return SigningKeyPage(self._version, response, self._solution) - :returns: Fetched SigningKeyInstance - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyInstance + async def get_page_async(self, target_url: str) -> SigningKeyPage: """ - return self._proxy.fetch() + 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 - def update(self, friendly_name=values.unset): + :returns: Page of SigningKeyInstance """ - Update the SigningKeyInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return SigningKeyPage(self._version, response, self._solution) - :param unicode friendly_name: The friendly_name + def get(self, sid: str) -> SigningKeyContext: + """ + Constructs a SigningKeyContext - :returns: Updated SigningKeyInstance - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyInstance + :param sid: """ - return self._proxy.update(friendly_name=friendly_name, ) + return SigningKeyContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def delete(self): + def __call__(self, sid: str) -> SigningKeyContext: """ - Deletes the SigningKeyInstance + Constructs a SigningKeyContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: """ - return self._proxy.delete() + return SigningKeyContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/api/v2010/account/sip/__init__.py b/twilio/rest/api/v2010/account/sip/__init__.py index 261e90f883..12c695ff72 100644 --- a/twilio/rest/api/v2010/account/sip/__init__.py +++ b/twilio/rest/api/v2010/account/sip/__init__.py @@ -1,156 +1,89 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base.instance_resource import InstanceResource +from typing import Optional + + from twilio.base.list_resource import ListResource -from twilio.base.page import Page +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 +from twilio.rest.api.v2010.account.sip.ip_access_control_list import ( + IpAccessControlListList, +) class SipList(ListResource): - """ """ - def __init__(self, version, account_sid): + def __init__(self, version: Version, account_sid: str): """ Initialize the SipList - :param Version version: Version that contains the resource - :param account_sid: A 34 character string that uniquely identifies this resource. + :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. - :returns: twilio.rest.api.v2010.account.sip.SipList - :rtype: twilio.rest.api.v2010.account.sip.SipList """ - super(SipList, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'account_sid': account_sid, } + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/SIP.json".format(**self._solution) - # Components - self._domains = None - self._regions = None - self._ip_access_control_lists = None - self._credential_lists = None + self._credential_lists: Optional[CredentialListList] = None + self._domains: Optional[DomainList] = None + self._ip_access_control_lists: Optional[IpAccessControlListList] = None @property - def domains(self): + def credential_lists(self) -> CredentialListList: """ - Access the domains + 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 - :returns: twilio.rest.api.v2010.account.sip.domain.DomainList - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainList + @property + def domains(self) -> DomainList: + """ + Access the domains """ if self._domains is None: - self._domains = DomainList(self._version, account_sid=self._solution['account_sid'], ) + self._domains = DomainList( + self._version, account_sid=self._solution["account_sid"] + ) return self._domains @property - def ip_access_control_lists(self): + def ip_access_control_lists(self) -> IpAccessControlListList: """ Access the ip_access_control_lists - - :returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListList - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListList """ if self._ip_access_control_lists is None: self._ip_access_control_lists = IpAccessControlListList( - self._version, - account_sid=self._solution['account_sid'], + self._version, account_sid=self._solution["account_sid"] ) return self._ip_access_control_lists - @property - def credential_lists(self): - """ - Access the credential_lists - - :returns: twilio.rest.api.v2010.account.sip.credential_list.CredentialListList - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListList - """ - if self._credential_lists is None: - self._credential_lists = CredentialListList( - self._version, - account_sid=self._solution['account_sid'], - ) - return self._credential_lists - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SipPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the SipPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.sip.SipPage - :rtype: twilio.rest.api.v2010.account.sip.SipPage - """ - super(SipPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of SipInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.sip.SipInstance - :rtype: twilio.rest.api.v2010.account.sip.SipInstance - """ - return SipInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SipInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid): - """ - Initialize the SipInstance - - :returns: twilio.rest.api.v2010.account.sip.SipInstance - :rtype: twilio.rest.api.v2010.account.sip.SipInstance - """ - super(SipInstance, self).__init__(version) - - # Context - self._context = None - self._solution = {'account_sid': account_sid, } - - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/api/v2010/account/sip/credential_list/__init__.py b/twilio/rest/api/v2010/account/sip/credential_list/__init__.py index 7b2d10a960..d1be747b6d 100644 --- a/twilio/rest/api/v2010/account/sip/credential_list/__init__.py +++ b/twilio/rest/api/v2010/account/sip/credential_list/__init__.py @@ -1,461 +1,653 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 CredentialListList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the CredentialListList +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") - :param Version version: Version that contains the resource - :param account_sid: A 34 character string that uniquely identifies this resource. + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[CredentialListContext] = None - :returns: twilio.rest.api.v2010.account.sip.credential_list.CredentialListList - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListList + @property + def _proxy(self) -> "CredentialListContext": """ - super(CredentialListList, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/SIP/CredentialLists.json'.format(**self._solution) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def stream(self, limit=None, page_size=None): + :returns: CredentialListContext for this 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + if self._context is None: + self._context = CredentialListContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the CredentialListInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists CredentialListInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the CredentialListInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "CredentialListInstance": """ - Retrieve a single page of CredentialListInstance records from the API. - Request is executed immediately + Fetch the CredentialListInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of CredentialListInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListPage + :returns: The fetched CredentialListInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return CredentialListPage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "CredentialListInstance": """ - Retrieve a specific page of CredentialListInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the CredentialListInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of CredentialListInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListPage + :returns: The fetched CredentialListInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return CredentialListPage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def create(self, friendly_name): + def update(self, friendly_name: str) -> "CredentialListInstance": """ - Create a new CredentialListInstance + Update the CredentialListInstance - :param unicode friendly_name: The friendly_name + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. - :returns: Newly created CredentialListInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance + :returns: The updated CredentialListInstance """ - data = values.of({'FriendlyName': friendly_name, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, + return self._proxy.update( + friendly_name=friendly_name, ) - return CredentialListInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - def get(self, sid): + async def update_async(self, friendly_name: str) -> "CredentialListInstance": """ - Constructs a CredentialListContext + Asynchronous coroutine to update the CredentialListInstance - :param sid: Fetch by unique credential Sid + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. - :returns: twilio.rest.api.v2010.account.sip.credential_list.CredentialListContext - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListContext + :returns: The updated CredentialListInstance """ - return CredentialListContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return await self._proxy.update_async( + friendly_name=friendly_name, + ) - def __call__(self, sid): + @property + def credentials(self) -> CredentialList: """ - Constructs a CredentialListContext - - :param sid: Fetch by unique credential Sid - - :returns: twilio.rest.api.v2010.account.sip.credential_list.CredentialListContext - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListContext + Access the credentials """ - return CredentialListContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.credentials - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class CredentialListPage(Page): - """ """ +class CredentialListContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str, sid: str): """ - Initialize the CredentialListPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: A 34 character string that uniquely identifies this resource. + Initialize the CredentialListContext - :returns: twilio.rest.api.v2010.account.sip.credential_list.CredentialListPage - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListPage + :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(CredentialListPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SIP/CredentialLists/{sid}.json".format( + **self._solution + ) - def get_instance(self, payload): + self._credentials: Optional[CredentialList] = None + + def delete(self) -> bool: """ - Build an instance of CredentialListInstance + Deletes the CredentialListInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance + :returns: True if delete succeeds, False otherwise """ - return CredentialListInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the CredentialListInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class CredentialListContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, account_sid, sid): + def fetch(self) -> CredentialListInstance: """ - Initialize the CredentialListContext + Fetch the CredentialListInstance - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param sid: Fetch by unique credential Sid - :returns: twilio.rest.api.v2010.account.sip.credential_list.CredentialListContext - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListContext + :returns: The fetched CredentialListInstance """ - super(CredentialListContext, self).__init__(version) - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/SIP/CredentialLists/{sid}.json'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - # Dependents - self._credentials = None + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return CredentialListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialListInstance: """ - Fetch a CredentialListInstance + Asynchronous coroutine to fetch the CredentialListInstance + - :returns: Fetched CredentialListInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance + :returns: The fetched CredentialListInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def update(self, friendly_name): + def update(self, friendly_name: str) -> CredentialListInstance: """ Update the CredentialListInstance - :param unicode friendly_name: The friendly_name + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. - :returns: Updated CredentialListInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance + :returns: The updated CredentialListInstance """ - data = values.of({'FriendlyName': friendly_name, }) + + 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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) return CredentialListInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def update_async(self, friendly_name: str) -> CredentialListInstance: """ - Deletes the CredentialListInstance + Asynchronous coroutine to update the CredentialListInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. + + :returns: The updated CredentialListInstance """ - return self._version.delete('delete', self._uri) + + 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): + def credentials(self) -> CredentialList: """ Access the credentials - - :returns: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialList - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialList """ if self._credentials is None: self._credentials = CredentialList( self._version, - account_sid=self._solution['account_sid'], - credential_list_sid=self._solution['sid'], + self._solution["account_sid"], + self._solution["sid"], ) return self._credentials - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class CredentialListInstance(InstanceResource): - """ """ +class CredentialListPage(Page): - def __init__(self, version, payload, account_sid, sid=None): + def get_instance(self, payload: Dict[str, Any]) -> CredentialListInstance: """ - Initialize the CredentialListInstance + Build an instance of CredentialListInstance - :returns: twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance + :param payload: Payload response from the API """ - super(CredentialListInstance, self).__init__(version) + return CredentialListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'friendly_name': payload['friendly_name'], - 'sid': payload['sid'], - 'subresource_uris': payload['subresource_uris'], - 'uri': payload['uri'], - } + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } - @property - def _proxy(self): +class CredentialListList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: CredentialListContext for this CredentialListInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListContext """ - if self._context is None: - self._context = CredentialListContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + super().__init__(version) - @property - def account_sid(self): + # 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: """ - :returns: The unique sid that identifies this account - :rtype: unicode + Create the CredentialListInstance + + :param friendly_name: A human readable descriptive text that describes the CredentialList, up to 64 characters long. + + :returns: The created CredentialListInstance """ - return self._properties['account_sid'] - @property - def date_created(self): + 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: """ - :returns: The date this resource was created - :rtype: datetime + 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 """ - return self._properties['date_created'] - @property - def date_updated(self): + 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]: """ - :returns: The date this resource was last updated - :rtype: datetime + 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 """ - return self._properties['date_updated'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def friendly_name(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialListInstance]: """ - :returns: The friendly_name - :rtype: unicode + 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 """ - return self._properties['friendly_name'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def sid(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialListInstance]: """ - :returns: A string that uniquely identifies this credential - :rtype: unicode + 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 self._properties['sid'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def subresource_uris(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialListInstance]: """ - :returns: The subresource_uris - :rtype: unicode + 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 self._properties['subresource_uris'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def uri(self): + 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: """ - :returns: The URI for this resource - :rtype: unicode + 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 """ - return self._properties['uri'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def fetch(self): + 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: """ - Fetch a CredentialListInstance + Retrieve a specific page of CredentialListInstance records from the API. + Request is executed immediately - :returns: Fetched CredentialListInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialListInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return CredentialListPage(self._version, response, self._solution) - def update(self, friendly_name): + async def get_page_async(self, target_url: str) -> CredentialListPage: """ - Update the CredentialListInstance + Asynchronously retrieve a specific page of CredentialListInstance records from the API. + Request is executed immediately - :param unicode friendly_name: The friendly_name + :param target_url: API-generated URL for the requested results page - :returns: Updated CredentialListInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance + :returns: Page of CredentialListInstance """ - return self._proxy.update(friendly_name, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialListPage(self._version, response, self._solution) - def delete(self): + def get(self, sid: str) -> CredentialListContext: """ - Deletes the CredentialListInstance + Constructs a CredentialListContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The credential list Sid that uniquely identifies this resource """ - return self._proxy.delete() + return CredentialListContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - @property - def credentials(self): + def __call__(self, sid: str) -> CredentialListContext: """ - Access the credentials + Constructs a CredentialListContext - :returns: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialList - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialList + :param sid: The credential list Sid that uniquely identifies this resource """ - return self._proxy.credentials + return CredentialListContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/api/v2010/account/sip/credential_list/credential.py b/twilio/rest/api/v2010/account/sip/credential_list/credential.py index 12073aaf4a..9c52a110e0 100644 --- a/twilio/rest/api/v2010/account/sip/credential_list/credential.py +++ b/twilio/rest/api/v2010/account/sip/credential_list/credential.py @@ -1,467 +1,666 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 CredentialList(ListResource): - """ """ +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 - def __init__(self, version, account_sid, credential_list_sid): + @property + def _proxy(self) -> "CredentialContext": """ - Initialize the CredentialList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param credential_list_sid: The credential_list_sid + :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 - :returns: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialList - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialList + def delete(self) -> bool: """ - super(CredentialList, self).__init__(version) + Deletes the CredentialInstance - # 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 stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + return self._proxy.delete() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance] + + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "CredentialInstance": + """ + Fetch the CredentialInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + return self._proxy.fetch() + + async def fetch_async(self) -> "CredentialInstance": + """ + Asynchronous coroutine to fetch the CredentialInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance] + :returns: The fetched CredentialInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def update( + self, password: Union[str, object] = values.unset + ) -> "CredentialInstance": """ - Retrieve a single page of CredentialInstance records from the API. - Request is executed immediately + Update the CredentialInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :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: Page of CredentialInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialPage + :returns: The updated CredentialInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.update( + password=password, + ) - response = self._version.page( - 'GET', - self._uri, - params=params, + 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, ) - return CredentialPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get_page(self, target_url): + :returns: Machine friendly representation """ - Retrieve a specific page of CredentialInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param str target_url: API-generated URL for the requested results page - :returns: Page of CredentialInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialPage +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. """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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 ) - return CredentialPage(self._version, response, self._solution) + def delete(self) -> bool: + """ + Deletes the CredentialInstance + - def create(self, username, password): + :returns: True if delete succeeds, False otherwise """ - Create a new CredentialInstance - :param unicode username: The username - :param unicode password: The password + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - :returns: Newly created CredentialInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance + async def delete_async(self) -> bool: """ - data = values.of({'Username': username, 'Password': password, }) + Asynchronous coroutine that deletes the CredentialInstance - payload = self._version.create( - 'POST', - self._uri, - data=data, + + :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'], + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=self._solution["sid"], ) - def get(self, sid): + async def fetch_async(self) -> CredentialInstance: """ - Constructs a CredentialContext + Asynchronous coroutine to fetch the CredentialInstance - :param sid: The sid - :returns: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialContext - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialContext + :returns: The fetched CredentialInstance """ - return CredentialContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CredentialInstance( self._version, - account_sid=self._solution['account_sid'], - credential_list_sid=self._solution['credential_list_sid'], - sid=sid, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=self._solution["sid"], ) - def __call__(self, sid): + def update(self, password: Union[str, object] = values.unset) -> CredentialInstance: """ - Constructs a CredentialContext + Update the CredentialInstance - :param sid: The sid + :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: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialContext - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialContext + :returns: The updated CredentialInstance """ - return CredentialContext( + + 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, - account_sid=self._solution['account_sid'], - credential_list_sid=self._solution['credential_list_sid'], - sid=sid, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + async def update_async( + self, password: Union[str, object] = values.unset + ) -> CredentialInstance: """ - Provide a friendly representation + Asynchronous coroutine to update the CredentialInstance - :returns: Machine friendly representation - :rtype: str + :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 '' + data = values.of( + { + "Password": password, + } + ) + headers = values.of({}) -class CredentialPage(Page): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, response, solution): - """ - Initialize the CredentialPage + 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"], + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The account_sid - :param credential_list_sid: The credential_list_sid + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialPage - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialPage + :returns: Machine friendly representation """ - super(CredentialPage, self).__init__(version, response) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Path Solution - self._solution = solution - def get_instance(self, payload): +class CredentialPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: """ Build an instance of CredentialInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.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'], + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class CredentialContext(InstanceContext): - """ """ +class CredentialList(ListResource): - def __init__(self, version, account_sid, credential_list_sid, sid): + def __init__(self, version: Version, account_sid: str, credential_list_sid: str): """ - Initialize the CredentialContext + Initialize the CredentialList - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param credential_list_sid: The credential_list_sid - :param sid: The sid + :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. - :returns: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialContext - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialContext """ - super(CredentialContext, self).__init__(version) + super().__init__(version) # Path Solution self._solution = { - 'account_sid': account_sid, - 'credential_list_sid': credential_list_sid, - 'sid': sid, + "account_sid": account_sid, + "credential_list_sid": credential_list_sid, } - self._uri = '/Accounts/{account_sid}/SIP/CredentialLists/{credential_list_sid}/Credentials/{sid}.json'.format(**self._solution) + self._uri = "/Accounts/{account_sid}/SIP/CredentialLists/{credential_list_sid}/Credentials.json".format( + **self._solution + ) - def fetch(self): + def create(self, username: str, password: str) -> CredentialInstance: """ - Fetch a CredentialInstance + Create the CredentialInstance - :returns: Fetched CredentialInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.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 """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], ) - def update(self, password=values.unset): + async def create_async(self, username: str, password: str) -> CredentialInstance: """ - Update the CredentialInstance + Asynchronously create the CredentialInstance - :param unicode password: The password + :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: Updated CredentialInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance + :returns: The created CredentialInstance """ - data = values.of({'Password': password, }) - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], ) - def delete(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialInstance]: """ - Deletes the 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. - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - def __repr__(self): + :returns: Generator that will yield up to limit results """ - Provide a friendly representation + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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. -class CredentialInstance(InstanceResource): - """ """ + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - def __init__(self, version, payload, account_sid, credential_list_sid, - sid=None): + :returns: Generator that will yield up to limit results """ - Initialize the CredentialInstance + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - :returns: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: """ - super(CredentialInstance, self).__init__(version) + Lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'credential_list_sid': payload['credential_list_sid'], - 'username': payload['username'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'uri': payload['uri'], - } + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - # Context - self._context = None - self._solution = { - 'account_sid': account_sid, - 'credential_list_sid': credential_list_sid, - 'sid': sid or self._properties['sid'], - } + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def _proxy(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: CredentialContext for this CredentialInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialContext + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - 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 [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, ) - return self._context + ] - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + 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: """ - return self._properties['sid'] + Retrieve a single page of CredentialInstance records from the API. + Request is executed immediately - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_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 - @property - def credential_list_sid(self): - """ - :returns: The credential_list_sid - :rtype: unicode + :returns: Page of CredentialInstance """ - return self._properties['credential_list_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def username(self): - """ - :returns: The username - :rtype: unicode - """ - return self._properties['username'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + headers["Accept"] = "application/json" - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime + 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: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page of CredentialInstance records from the API. + Request is executed immediately - @property - def uri(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The uri - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['uri'] + 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 - def fetch(self): + :returns: Page of CredentialInstance """ - Fetch a CredentialInstance + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response, self._solution) - :returns: Fetched CredentialInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance + async def get_page_async(self, target_url: str) -> CredentialPage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately - def update(self, password=values.unset): + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance """ - Update the CredentialInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response, self._solution) - :param unicode password: The password + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext - :returns: Updated CredentialInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance + :param sid: The unique id that identifies the resource to update. """ - return self._proxy.update(password=password, ) + return CredentialContext( + self._version, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=sid, + ) - def delete(self): + def __call__(self, sid: str) -> CredentialContext: """ - Deletes the CredentialInstance + Constructs a CredentialContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The unique id that identifies the resource to update. """ - return self._proxy.delete() + return CredentialContext( + self._version, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/api/v2010/account/sip/domain/__init__.py b/twilio/rest/api/v2010/account/sip/domain/__init__.py index d205373f57..0a45e68273 100644 --- a/twilio/rest/api/v2010/account/sip/domain/__init__.py +++ b/twilio/rest/api/v2010/account/sip/domain/__init__.py @@ -1,649 +1,977 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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.credential_list_mapping import CredentialListMappingList -from twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping import IpAccessControlListMappingList - +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 DomainList(ListResource): - """ """ - def __init__(self, version, account_sid): - """ - Initialize the DomainList +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") - :param Version version: Version that contains the resource - :param account_sid: A 34 character string that uniquely identifies this resource. + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[DomainContext] = None - :returns: twilio.rest.api.v2010.account.sip.domain.DomainList - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainList + @property + def _proxy(self) -> "DomainContext": """ - super(DomainList, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/SIP/Domains.json'.format(**self._solution) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def stream(self, limit=None, page_size=None): + :returns: DomainContext for this 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + if self._context is None: + self._context = DomainContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.sip.domain.DomainInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the DomainInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists DomainInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the DomainInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.sip.domain.DomainInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "DomainInstance": """ - Retrieve a single page of DomainInstance records from the API. - Request is executed immediately + Fetch the DomainInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of DomainInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainPage + :returns: The fetched DomainInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + async def fetch_async(self) -> "DomainInstance": + """ + Asynchronous coroutine to fetch the DomainInstance - return DomainPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched DomainInstance """ - Retrieve a specific page of DomainInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_async() - :param str target_url: API-generated URL for the requested results page + 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 - :returns: Page of DomainInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainPage + :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 """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, ) - return DomainPage(self._version, response, self._solution) - - def create(self, domain_name, friendly_name=values.unset, - auth_type=values.unset, voice_url=values.unset, - voice_method=values.unset, voice_fallback_url=values.unset, - voice_fallback_method=values.unset, - voice_status_callback_url=values.unset, - voice_status_callback_method=values.unset, - sip_registration=values.unset): - """ - Create a new DomainInstance - - :param unicode domain_name: The unique address on Twilio to route SIP traffic - :param unicode friendly_name: A user-specified, human-readable name for the trigger. - :param unicode auth_type: The types of authentication mapped to the domain - :param unicode voice_url: URL Twilio will request when receiving a call - :param unicode voice_method: HTTP method to use with voice_url - :param unicode voice_fallback_url: URL Twilio will request if an error occurs in executing TwiML - :param unicode voice_fallback_method: HTTP method used with voice_fallback_url - :param unicode voice_status_callback_url: URL that Twilio will request with status updates - :param unicode voice_status_callback_method: The voice_status_callback_method - :param bool sip_registration: The sip_registration - - :returns: Newly created DomainInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainInstance - """ - data = values.of({ - 'DomainName': domain_name, - 'FriendlyName': friendly_name, - 'AuthType': auth_type, - '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': sip_registration, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, + 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, ) - return DomainInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - def get(self, sid): + @property + def auth(self) -> AuthTypesList: """ - Constructs a DomainContext - - :param sid: Fetch by unique Domain Sid - - :returns: twilio.rest.api.v2010.account.sip.domain.DomainContext - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainContext + Access the auth """ - return DomainContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.auth - def __call__(self, sid): + @property + def credential_list_mappings(self) -> CredentialListMappingList: """ - Constructs a DomainContext - - :param sid: Fetch by unique Domain Sid + Access the credential_list_mappings + """ + return self._proxy.credential_list_mappings - :returns: twilio.rest.api.v2010.account.sip.domain.DomainContext - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainContext + @property + def ip_access_control_list_mappings(self) -> IpAccessControlListMappingList: """ - return DomainContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + Access the ip_access_control_list_mappings + """ + return self._proxy.ip_access_control_list_mappings - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class DomainPage(Page): - """ """ +class DomainContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str, sid: str): """ - Initialize the DomainPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: A 34 character string that uniquely identifies this resource. + Initialize the DomainContext - :returns: twilio.rest.api.v2010.account.sip.domain.DomainPage - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainPage + :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(DomainPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of DomainInstance + Deletes the DomainInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.api.v2010.account.sip.domain.DomainInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainInstance + :returns: True if delete succeeds, False otherwise """ - return DomainInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the DomainInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class DomainContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, account_sid, sid): + def fetch(self) -> DomainInstance: """ - Initialize the DomainContext + Fetch the DomainInstance - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param sid: Fetch by unique Domain Sid - :returns: twilio.rest.api.v2010.account.sip.domain.DomainContext - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainContext + :returns: The fetched DomainInstance """ - super(DomainContext, self).__init__(version) - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/SIP/Domains/{sid}.json'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - # Dependents - self._ip_access_control_list_mappings = None - self._credential_list_mappings = None + return DomainInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - def fetch(self): + async def fetch_async(self) -> DomainInstance: """ - Fetch a DomainInstance + Asynchronous coroutine to fetch the DomainInstance - :returns: Fetched DomainInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainInstance + + :returns: The fetched DomainInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def update(self, auth_type=values.unset, friendly_name=values.unset, - voice_fallback_method=values.unset, voice_fallback_url=values.unset, - voice_method=values.unset, voice_status_callback_method=values.unset, - voice_status_callback_url=values.unset, voice_url=values.unset, - sip_registration=values.unset): + 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 unicode auth_type: The auth_type - :param unicode friendly_name: A user-specified, human-readable name for the trigger. - :param unicode voice_fallback_method: The voice_fallback_method - :param unicode voice_fallback_url: The voice_fallback_url - :param unicode voice_method: HTTP method to use with voice_url - :param unicode voice_status_callback_method: The voice_status_callback_method - :param unicode voice_status_callback_url: The voice_status_callback_url - :param unicode voice_url: The voice_url - :param bool sip_registration: The sip_registration - - :returns: Updated DomainInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainInstance - """ - data = values.of({ - 'AuthType': auth_type, - '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': sip_registration, - }) + :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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) return DomainInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def delete(self): - """ - Deletes the DomainInstance + 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({}) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + 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 ip_access_control_list_mappings(self): + def auth(self) -> AuthTypesList: """ - Access the ip_access_control_list_mappings - - :returns: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingList - :rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingList + Access the auth """ - if self._ip_access_control_list_mappings is None: - self._ip_access_control_list_mappings = IpAccessControlListMappingList( + if self._auth is None: + self._auth = AuthTypesList( self._version, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['sid'], + self._solution["account_sid"], + self._solution["sid"], ) - return self._ip_access_control_list_mappings + return self._auth @property - def credential_list_mappings(self): + def credential_list_mappings(self) -> CredentialListMappingList: """ Access the credential_list_mappings - - :returns: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingList - :rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingList """ if self._credential_list_mappings is None: self._credential_list_mappings = CredentialListMappingList( self._version, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['sid'], + self._solution["account_sid"], + self._solution["sid"], ) return self._credential_list_mappings - def __repr__(self): + @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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class DomainInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid, sid=None): - """ - Initialize the DomainInstance - - :returns: twilio.rest.api.v2010.account.sip.domain.DomainInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainInstance - """ - super(DomainInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'api_version': payload['api_version'], - 'auth_type': payload['auth_type'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'domain_name': payload['domain_name'], - 'friendly_name': payload['friendly_name'], - 'sid': payload['sid'], - 'uri': payload['uri'], - 'voice_fallback_method': payload['voice_fallback_method'], - 'voice_fallback_url': payload['voice_fallback_url'], - 'voice_method': payload['voice_method'], - 'voice_status_callback_method': payload['voice_status_callback_method'], - 'voice_status_callback_url': payload['voice_status_callback_url'], - 'voice_url': payload['voice_url'], - 'subresource_uris': payload['subresource_uris'], - 'sip_registration': payload['sip_registration'], - } - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } +class DomainPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> DomainInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of DomainInstance - :returns: DomainContext for this DomainInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = DomainContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + return DomainInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def account_sid(self): + def __repr__(self) -> str: """ - :returns: The unique id of the account that sent the message - :rtype: unicode - """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def api_version(self): - """ - :returns: The Twilio API version used to process the message - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['api_version'] + return "" - @property - def auth_type(self): - """ - :returns: The types of authentication mapped to the domain - :rtype: unicode - """ - return self._properties['auth_type'] - @property - def date_created(self): - """ - :returns: The date this resource was created - :rtype: datetime - """ - return self._properties['date_created'] +class DomainList(ListResource): - @property - def date_updated(self): - """ - :returns: The date this resource was last updated - :rtype: datetime + def __init__(self, version: Version, account_sid: str): """ - return self._properties['date_updated'] + Initialize the DomainList - @property - def domain_name(self): - """ - :returns: The unique address on Twilio to route SIP traffic - :rtype: unicode - """ - return self._properties['domain_name'] + :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. - @property - def friendly_name(self): """ - :returns: A user-specified, human-readable name for the trigger. - :rtype: unicode - """ - return self._properties['friendly_name'] + super().__init__(version) - @property - def sid(self): - """ - :returns: A string that uniquely identifies the SIP Domain - :rtype: unicode - """ - return self._properties['sid'] + # 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"}) - @property - def uri(self): - """ - :returns: The URI for this resource - :rtype: unicode - """ - return self._properties['uri'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def voice_fallback_method(self): - """ - :returns: HTTP method used with voice_fallback_url - :rtype: unicode - """ - return self._properties['voice_fallback_method'] + headers["Accept"] = "application/json" - @property - def voice_fallback_url(self): - """ - :returns: URL Twilio will request if an error occurs in executing TwiML - :rtype: unicode - """ - return self._properties['voice_fallback_url'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def voice_method(self): - """ - :returns: HTTP method to use with voice_url - :rtype: unicode - """ - return self._properties['voice_method'] + return DomainInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def voice_status_callback_method(self): + 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]: """ - :returns: The voice_status_callback_method - :rtype: unicode + 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 """ - return self._properties['voice_status_callback_method'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def voice_status_callback_url(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DomainInstance]: """ - :returns: URL that Twilio will request with status updates - :rtype: unicode + 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 """ - return self._properties['voice_status_callback_url'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def voice_url(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DomainInstance]: """ - :returns: URL Twilio will request when receiving a call - :rtype: unicode + 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 self._properties['voice_url'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def subresource_uris(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DomainInstance]: """ - :returns: The subresource_uris - :rtype: unicode + 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 self._properties['subresource_uris'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def sip_registration(self): + 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: """ - :returns: If SIP registration is allowed - :rtype: bool + 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 """ - return self._properties['sip_registration'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def fetch(self): + 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: """ - Fetch a DomainInstance + 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: Fetched DomainInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainInstance + :returns: Page of DomainInstance """ - return self._proxy.fetch() + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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 update(self, auth_type=values.unset, friendly_name=values.unset, - voice_fallback_method=values.unset, voice_fallback_url=values.unset, - voice_method=values.unset, voice_status_callback_method=values.unset, - voice_status_callback_url=values.unset, voice_url=values.unset, - sip_registration=values.unset): + def get_page(self, target_url: str) -> DomainPage: """ - Update the DomainInstance + Retrieve a specific page of DomainInstance records from the API. + Request is executed immediately - :param unicode auth_type: The auth_type - :param unicode friendly_name: A user-specified, human-readable name for the trigger. - :param unicode voice_fallback_method: The voice_fallback_method - :param unicode voice_fallback_url: The voice_fallback_url - :param unicode voice_method: HTTP method to use with voice_url - :param unicode voice_status_callback_method: The voice_status_callback_method - :param unicode voice_status_callback_url: The voice_status_callback_url - :param unicode voice_url: The voice_url - :param bool sip_registration: The sip_registration + :param target_url: API-generated URL for the requested results page - :returns: Updated DomainInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainInstance + :returns: Page of DomainInstance """ - return self._proxy.update( - auth_type=auth_type, - 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, - ) + response = self._version.domain.twilio.request("GET", target_url) + return DomainPage(self._version, response, self._solution) - def delete(self): + async def get_page_async(self, target_url: str) -> DomainPage: """ - Deletes the DomainInstance + Asynchronously retrieve a specific page of DomainInstance records from the API. + Request is executed immediately - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param target_url: API-generated URL for the requested results page + + :returns: Page of DomainInstance """ - return self._proxy.delete() + response = await self._version.domain.twilio.request_async("GET", target_url) + return DomainPage(self._version, response, self._solution) - @property - def ip_access_control_list_mappings(self): + def get(self, sid: str) -> DomainContext: """ - Access the ip_access_control_list_mappings + Constructs a DomainContext - :returns: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingList - :rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingList + :param sid: The Twilio-provided string that uniquely identifies the SipDomain resource to update. """ - return self._proxy.ip_access_control_list_mappings + return DomainContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - @property - def credential_list_mappings(self): + def __call__(self, sid: str) -> DomainContext: """ - Access the credential_list_mappings + Constructs a DomainContext - :returns: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingList - :rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingList + :param sid: The Twilio-provided string that uniquely identifies the SipDomain resource to update. """ - return self._proxy.credential_list_mappings + return DomainContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 "" 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 "" 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 "".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 "".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 "" + + +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 "" 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 ( + "".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 ( + "".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 "" + + +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 "" 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 "" 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 "".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 "".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 "" + + +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 "" 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 index 5a9c7be103..b520f4813a 100644 --- a/twilio/rest/api/v2010/account/sip/domain/credential_list_mapping.py +++ b/twilio/rest/api/v2010/account/sip/domain/credential_list_mapping.py @@ -1,425 +1,568 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 CredentialListMappingList(ListResource): - """ """ +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 - def __init__(self, version, account_sid, domain_sid): + @property + def _proxy(self) -> "CredentialListMappingContext": """ - Initialize the CredentialListMappingList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param domain_sid: A string that uniquely identifies the SIP Domain + :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 - :returns: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingList - :rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingList + def delete(self) -> bool: """ - super(CredentialListMappingList, self).__init__(version) + Deletes the CredentialListMappingInstance - # 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): + :returns: True if delete succeeds, False otherwise """ - Create a new CredentialListMappingInstance - - :param unicode credential_list_sid: The credential_list_sid + return self._proxy.delete() - :returns: Newly created CredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingInstance + async def delete_async(self) -> bool: """ - data = values.of({'CredentialListSid': credential_list_sid, }) + Asynchronous coroutine that deletes the CredentialListMappingInstance - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - return CredentialListMappingInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - ) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def stream(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the CredentialListMappingInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingInstance] + :returns: The fetched CredentialListMappingInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(page_size=limits['page_size'], ) + async def fetch_async(self) -> "CredentialListMappingInstance": + """ + Asynchronous coroutine to fetch the CredentialListMappingInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + return await self._proxy.fetch_async() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingInstance] + def __repr__(self) -> str: """ - return list(self.stream(limit=limit, page_size=page_size, )) + Provide a friendly representation - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + :returns: Machine friendly representation """ - Retrieve a single page of CredentialListMappingInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of CredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingPage +class CredentialListMappingContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str): """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the CredentialListMappingContext - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + :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) - return CredentialListMappingPage(self._version, response, self._solution) + # 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 get_page(self, target_url): + def delete(self) -> bool: """ - Retrieve a specific page of CredentialListMappingInstance records from the API. - Request is executed immediately + Deletes the CredentialListMappingInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of CredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingPage + :returns: True if delete succeeds, False otherwise """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return CredentialListMappingPage(self._version, response, self._solution) + headers = values.of({}) - def get(self, sid): + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Constructs a CredentialListMappingContext + Asynchronous coroutine that deletes the CredentialListMappingInstance - :param sid: The sid - :returns: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingContext - :rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingContext + :returns: True if delete succeeds, False otherwise """ - return CredentialListMappingContext( - self._version, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - sid=sid, + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers ) - def __call__(self, sid): + def fetch(self) -> CredentialListMappingInstance: """ - Constructs a CredentialListMappingContext + Fetch the CredentialListMappingInstance - :param sid: The sid - :returns: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingContext - :rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingContext + :returns: The fetched CredentialListMappingInstance """ - return CredentialListMappingContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CredentialListMappingInstance( self._version, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - sid=sid, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + async def fetch_async(self) -> CredentialListMappingInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the CredentialListMappingInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched CredentialListMappingInstance """ - return '' + headers = values.of({}) -class CredentialListMappingPage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): - """ - Initialize the CredentialListMappingPage + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The account_sid - :param domain_sid: A string that uniquely identifies the SIP Domain + return CredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingPage - :rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingPage + def __repr__(self) -> str: """ - super(CredentialListMappingPage, self).__init__(version, response) + Provide a friendly representation - # Path Solution - self._solution = solution + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - def get_instance(self, payload): + +class CredentialListMappingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialListMappingInstance: """ Build an instance of CredentialListMappingInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.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'], + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class CredentialListMappingContext(InstanceContext): - """ """ +class CredentialListMappingList(ListResource): - def __init__(self, version, account_sid, domain_sid, sid): + def __init__(self, version: Version, account_sid: str, domain_sid: str): """ - Initialize the CredentialListMappingContext + Initialize the CredentialListMappingList - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param domain_sid: The domain_sid - :param sid: The sid + :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. - :returns: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingContext - :rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingContext """ - super(CredentialListMappingContext, self).__init__(version) + 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) + 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 fetch(self): + def create(self, credential_list_sid: str) -> CredentialListMappingInstance: """ - Fetch a CredentialListMappingInstance + Create the CredentialListMappingInstance - :returns: Fetched CredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.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 """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], ) - def delete(self): + async def create_async( + self, credential_list_sid: str + ) -> CredentialListMappingInstance: """ - Deletes the CredentialListMappingInstance + Asynchronously create the CredentialListMappingInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :param credential_list_sid: A 34 character string that uniquely identifies the CredentialList resource to map to the SIP domain. - def __repr__(self): + :returns: The created CredentialListMappingInstance """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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" -class CredentialListMappingInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, payload, account_sid, domain_sid, sid=None): - """ - Initialize the CredentialListMappingInstance + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingInstance - """ - super(CredentialListMappingInstance, self).__init__(version) + return CredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'friendly_name': payload['friendly_name'], - 'sid': payload['sid'], - 'uri': payload['uri'], - 'subresource_uris': payload['subresource_uris'], - } + 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. - # Context - self._context = None - self._solution = { - 'account_sid': account_sid, - 'domain_sid': domain_sid, - 'sid': sid or self._properties['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) - @property - def _proxy(self): + :returns: Generator that will yield up to limit results """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - :returns: CredentialListMappingContext for this CredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingContext - """ - 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 + return self._version.stream(page, limits["limit"]) - @property - def account_sid(self): + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialListMappingInstance]: """ - :returns: The account_sid - :rtype: unicode + 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 """ - return self._properties['account_sid'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def date_created(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialListMappingInstance]: """ - :returns: The date_created - :rtype: datetime + 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 self._properties['date_created'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def date_updated(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialListMappingInstance]: """ - :returns: The date_updated - :rtype: datetime + 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 self._properties['date_updated'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def friendly_name(self): + 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: """ - :returns: The friendly_name - :rtype: unicode + 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 """ - return self._properties['friendly_name'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def sid(self): + headers = values.of({"Content-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: """ - :returns: The sid - :rtype: unicode + 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 """ - return self._properties['sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def uri(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The uri - :rtype: unicode + 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 """ - return self._properties['uri'] + response = self._version.domain.twilio.request("GET", target_url) + return CredentialListMappingPage(self._version, response, self._solution) - @property - def subresource_uris(self): + async def get_page_async(self, target_url: str) -> CredentialListMappingPage: """ - :returns: The subresource_uris - :rtype: unicode + 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 """ - return self._properties['subresource_uris'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialListMappingPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> CredentialListMappingContext: """ - Fetch a CredentialListMappingInstance + Constructs a CredentialListMappingContext - :returns: Fetched CredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingInstance + :param sid: A 34 character string that uniquely identifies the resource to fetch. """ - return self._proxy.fetch() + return CredentialListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) - def delete(self): + def __call__(self, sid: str) -> CredentialListMappingContext: """ - Deletes the CredentialListMappingInstance + Constructs a CredentialListMappingContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: A 34 character string that uniquely identifies the resource to fetch. """ - return self._proxy.delete() + return CredentialListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 index ded6097768..4dfecfe826 100644 --- 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 @@ -1,425 +1,574 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 IpAccessControlListMappingList(ListResource): - """ """ +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 - def __init__(self, version, account_sid, domain_sid): + @property + def _proxy(self) -> "IpAccessControlListMappingContext": """ - Initialize the IpAccessControlListMappingList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param domain_sid: A string that uniquely identifies the SIP Domain + :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 - :returns: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingList - :rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingList + def delete(self) -> bool: """ - super(IpAccessControlListMappingList, self).__init__(version) + Deletes the IpAccessControlListMappingInstance - # 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): + :returns: True if delete succeeds, False otherwise """ - Create a new IpAccessControlListMappingInstance - - :param unicode ip_access_control_list_sid: The ip_access_control_list_sid + return self._proxy.delete() - :returns: Newly created IpAccessControlListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingInstance + async def delete_async(self) -> bool: """ - data = values.of({'IpAccessControlListSid': ip_access_control_list_sid, }) + Asynchronous coroutine that deletes the IpAccessControlListMappingInstance - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - return IpAccessControlListMappingInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - ) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def stream(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the IpAccessControlListMappingInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingInstance] + :returns: The fetched IpAccessControlListMappingInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(page_size=limits['page_size'], ) + async def fetch_async(self) -> "IpAccessControlListMappingInstance": + """ + Asynchronous coroutine to fetch the IpAccessControlListMappingInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + return await self._proxy.fetch_async() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingInstance] + def __repr__(self) -> str: """ - return list(self.stream(limit=limit, page_size=page_size, )) + Provide a friendly representation - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + :returns: Machine friendly representation """ - Retrieve a single page of IpAccessControlListMappingInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of IpAccessControlListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingPage +class IpAccessControlListMappingContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str): """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the IpAccessControlListMappingContext - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + :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) - return IpAccessControlListMappingPage(self._version, response, self._solution) + # 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 get_page(self, target_url): + def delete(self) -> bool: """ - Retrieve a specific page of IpAccessControlListMappingInstance records from the API. - Request is executed immediately + Deletes the IpAccessControlListMappingInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of IpAccessControlListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingPage + :returns: True if delete succeeds, False otherwise """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return IpAccessControlListMappingPage(self._version, response, self._solution) + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def get(self, sid): + async def delete_async(self) -> bool: """ - Constructs a IpAccessControlListMappingContext + Asynchronous coroutine that deletes the IpAccessControlListMappingInstance - :param sid: The sid - :returns: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingContext - :rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingContext + :returns: True if delete succeeds, False otherwise """ - return IpAccessControlListMappingContext( - self._version, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - sid=sid, + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers ) - def __call__(self, sid): + def fetch(self) -> IpAccessControlListMappingInstance: """ - Constructs a IpAccessControlListMappingContext + Fetch the IpAccessControlListMappingInstance - :param sid: The sid - :returns: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingContext - :rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingContext + :returns: The fetched IpAccessControlListMappingInstance """ - return IpAccessControlListMappingContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return IpAccessControlListMappingInstance( self._version, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - sid=sid, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + async def fetch_async(self) -> IpAccessControlListMappingInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the IpAccessControlListMappingInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched IpAccessControlListMappingInstance """ - return '' + headers = values.of({}) -class IpAccessControlListMappingPage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): - """ - Initialize the IpAccessControlListMappingPage + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The account_sid - :param domain_sid: A string that uniquely identifies the SIP Domain + return IpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingPage - :rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingPage + def __repr__(self) -> str: """ - super(IpAccessControlListMappingPage, self).__init__(version, response) + Provide a friendly representation - # Path Solution - self._solution = solution + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class IpAccessControlListMappingPage(Page): - def get_instance(self, payload): + def get_instance( + self, payload: Dict[str, Any] + ) -> IpAccessControlListMappingInstance: """ Build an instance of IpAccessControlListMappingInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.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'], + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class IpAccessControlListMappingContext(InstanceContext): - """ """ +class IpAccessControlListMappingList(ListResource): - def __init__(self, version, account_sid, domain_sid, sid): + def __init__(self, version: Version, account_sid: str, domain_sid: str): """ - Initialize the IpAccessControlListMappingContext + Initialize the IpAccessControlListMappingList - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param domain_sid: The domain_sid - :param sid: The sid + :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. - :returns: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingContext - :rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingContext """ - super(IpAccessControlListMappingContext, self).__init__(version) + 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) + 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 fetch(self): + def create( + self, ip_access_control_list_sid: str + ) -> IpAccessControlListMappingInstance: """ - Fetch a 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: Fetched IpAccessControlListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingInstance + :returns: The created IpAccessControlListMappingInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], ) - def delete(self): + async def create_async( + self, ip_access_control_list_sid: str + ) -> IpAccessControlListMappingInstance: """ - Deletes the IpAccessControlListMappingInstance + Asynchronously create the IpAccessControlListMappingInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :param ip_access_control_list_sid: The unique id of the IP access control list to map to the SIP domain. - def __repr__(self): + :returns: The created IpAccessControlListMappingInstance """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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" -class IpAccessControlListMappingInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, payload, account_sid, domain_sid, sid=None): - """ - Initialize the IpAccessControlListMappingInstance + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingInstance - """ - super(IpAccessControlListMappingInstance, self).__init__(version) + return IpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'friendly_name': payload['friendly_name'], - 'sid': payload['sid'], - 'uri': payload['uri'], - 'subresource_uris': payload['subresource_uris'], - } + 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. - # Context - self._context = None - self._solution = { - 'account_sid': account_sid, - 'domain_sid': domain_sid, - 'sid': sid or self._properties['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) - @property - def _proxy(self): + :returns: Generator that will yield up to limit results """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - :returns: IpAccessControlListMappingContext for this IpAccessControlListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingContext - """ - 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 + return self._version.stream(page, limits["limit"]) - @property - def account_sid(self): + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[IpAccessControlListMappingInstance]: """ - :returns: The account_sid - :rtype: unicode + 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 """ - return self._properties['account_sid'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def date_created(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAccessControlListMappingInstance]: """ - :returns: The date_created - :rtype: datetime + 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 self._properties['date_created'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def date_updated(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAccessControlListMappingInstance]: """ - :returns: The date_updated - :rtype: datetime + 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 self._properties['date_updated'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def friendly_name(self): + 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: """ - :returns: The friendly_name - :rtype: unicode + 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 """ - return self._properties['friendly_name'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def sid(self): + headers = values.of({"Content-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: """ - :returns: The sid - :rtype: unicode + 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 """ - return self._properties['sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def uri(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The uri - :rtype: unicode + 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 """ - return self._properties['uri'] + response = self._version.domain.twilio.request("GET", target_url) + return IpAccessControlListMappingPage(self._version, response, self._solution) - @property - def subresource_uris(self): + async def get_page_async(self, target_url: str) -> IpAccessControlListMappingPage: """ - :returns: The subresource_uris - :rtype: unicode + 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 """ - return self._properties['subresource_uris'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return IpAccessControlListMappingPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> IpAccessControlListMappingContext: """ - Fetch a IpAccessControlListMappingInstance + Constructs a IpAccessControlListMappingContext - :returns: Fetched IpAccessControlListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingInstance + :param sid: A 34 character string that uniquely identifies the resource to fetch. """ - return self._proxy.fetch() + return IpAccessControlListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) - def delete(self): + def __call__(self, sid: str) -> IpAccessControlListMappingContext: """ - Deletes the IpAccessControlListMappingInstance + Constructs a IpAccessControlListMappingContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: A 34 character string that uniquely identifies the resource to fetch. """ - return self._proxy.delete() + return IpAccessControlListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 index 0a5c529660..afa504c208 100644 --- 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 @@ -1,469 +1,657 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 - +from twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address import ( + IpAddressList, +) -class IpAccessControlListList(ListResource): - """ """ - def __init__(self, version, account_sid): - """ - Initialize the IpAccessControlListList +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") - :param Version version: Version that contains the resource - :param account_sid: A 34 character string that uniquely identifies this resource. + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[IpAccessControlListContext] = None - :returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListList - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListList + @property + def _proxy(self) -> "IpAccessControlListContext": """ - super(IpAccessControlListList, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/SIP/IpAccessControlLists.json'.format(**self._solution) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def stream(self, limit=None, page_size=None): + :returns: IpAccessControlListContext for this 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + if self._context is None: + self._context = IpAccessControlListContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the IpAccessControlListInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists IpAccessControlListInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the IpAccessControlListInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "IpAccessControlListInstance": """ - Retrieve a single page of IpAccessControlListInstance records from the API. - Request is executed immediately + Fetch the IpAccessControlListInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of IpAccessControlListInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListPage + :returns: The fetched IpAccessControlListInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return IpAccessControlListPage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "IpAccessControlListInstance": """ - Retrieve a specific page of IpAccessControlListInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the IpAccessControlListInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of IpAccessControlListInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListPage + :returns: The fetched IpAccessControlListInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return IpAccessControlListPage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def create(self, friendly_name): + def update(self, friendly_name: str) -> "IpAccessControlListInstance": """ - Create a new IpAccessControlListInstance + Update the IpAccessControlListInstance - :param unicode friendly_name: A human readable description of this resource + :param friendly_name: A human readable descriptive text, up to 255 characters long. - :returns: Newly created IpAccessControlListInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance + :returns: The updated IpAccessControlListInstance """ - data = values.of({'FriendlyName': friendly_name, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, + return self._proxy.update( + friendly_name=friendly_name, ) - return IpAccessControlListInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - ) - - def get(self, sid): + async def update_async(self, friendly_name: str) -> "IpAccessControlListInstance": """ - Constructs a IpAccessControlListContext + Asynchronous coroutine to update the IpAccessControlListInstance - :param sid: Fetch by unique ip-access-control-list Sid + :param friendly_name: A human readable descriptive text, up to 255 characters long. - :returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListContext - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListContext + :returns: The updated IpAccessControlListInstance """ - return IpAccessControlListContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return await self._proxy.update_async( + friendly_name=friendly_name, + ) - def __call__(self, sid): + @property + def ip_addresses(self) -> IpAddressList: """ - Constructs a IpAccessControlListContext - - :param sid: Fetch by unique ip-access-control-list Sid - - :returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListContext - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListContext + Access the ip_addresses """ - return IpAccessControlListContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return self._proxy.ip_addresses - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class IpAccessControlListPage(Page): - """ """ +class IpAccessControlListContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str, sid: str): """ - Initialize the IpAccessControlListPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: A 34 character string that uniquely identifies this resource. + Initialize the IpAccessControlListContext - :returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListPage - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListPage + :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(IpAccessControlListPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of IpAccessControlListInstance + Deletes the IpAccessControlListInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance + :returns: True if delete succeeds, False otherwise """ - return IpAccessControlListInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the IpAccessControlListInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class IpAccessControlListContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, account_sid, sid): + def fetch(self) -> IpAccessControlListInstance: """ - Initialize the IpAccessControlListContext + Fetch the IpAccessControlListInstance - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param sid: Fetch by unique ip-access-control-list Sid - :returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListContext - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListContext + :returns: The fetched IpAccessControlListInstance """ - super(IpAccessControlListContext, self).__init__(version) - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/SIP/IpAccessControlLists/{sid}.json'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - # Dependents - self._ip_addresses = None + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return IpAccessControlListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> IpAccessControlListInstance: """ - Fetch a IpAccessControlListInstance + Asynchronous coroutine to fetch the IpAccessControlListInstance + - :returns: Fetched IpAccessControlListInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance + :returns: The fetched IpAccessControlListInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def update(self, friendly_name): + def update(self, friendly_name: str) -> IpAccessControlListInstance: """ Update the IpAccessControlListInstance - :param unicode friendly_name: A human readable description of this resource + :param friendly_name: A human readable descriptive text, up to 255 characters long. - :returns: Updated IpAccessControlListInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance + :returns: The updated IpAccessControlListInstance """ - data = values.of({'FriendlyName': friendly_name, }) + + 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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) return IpAccessControlListInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def update_async(self, friendly_name: str) -> IpAccessControlListInstance: """ - Deletes the IpAccessControlListInstance + Asynchronous coroutine to update the IpAccessControlListInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param friendly_name: A human readable descriptive text, up to 255 characters long. + + :returns: The updated IpAccessControlListInstance """ - return self._version.delete('delete', self._uri) + + 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): + def ip_addresses(self) -> IpAddressList: """ Access the ip_addresses - - :returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressList - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressList """ if self._ip_addresses is None: self._ip_addresses = IpAddressList( self._version, - account_sid=self._solution['account_sid'], - ip_access_control_list_sid=self._solution['sid'], + self._solution["account_sid"], + self._solution["sid"], ) return self._ip_addresses - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class IpAccessControlListInstance(InstanceResource): - """ """ +class IpAccessControlListPage(Page): - def __init__(self, version, payload, account_sid, sid=None): + def get_instance(self, payload: Dict[str, Any]) -> IpAccessControlListInstance: """ - Initialize the IpAccessControlListInstance + Build an instance of IpAccessControlListInstance - :returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance + :param payload: Payload response from the API """ - super(IpAccessControlListInstance, self).__init__(version) + return IpAccessControlListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'friendly_name': payload['friendly_name'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'subresource_uris': payload['subresource_uris'], - 'uri': payload['uri'], - } + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } - @property - def _proxy(self): +class IpAccessControlListList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: IpAccessControlListContext for this IpAccessControlListInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListContext """ - if self._context is None: - self._context = IpAccessControlListContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + super().__init__(version) - @property - def sid(self): + # 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: """ - :returns: A string that uniquely identifies this resource - :rtype: unicode + Create the IpAccessControlListInstance + + :param friendly_name: A human readable descriptive text that describes the IpAccessControlList, up to 255 characters long. + + :returns: The created IpAccessControlListInstance """ - return self._properties['sid'] - @property - def account_sid(self): + 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: """ - :returns: The unique sid that identifies this account - :rtype: unicode + 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 """ - return self._properties['account_sid'] - @property - def friendly_name(self): + 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]: """ - :returns: A human readable description of this resource - :rtype: unicode + 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 """ - return self._properties['friendly_name'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def date_created(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[IpAccessControlListInstance]: """ - :returns: The date this resource was created - :rtype: datetime + 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 """ - return self._properties['date_created'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def date_updated(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAccessControlListInstance]: """ - :returns: The date this resource was last updated - :rtype: datetime + 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 self._properties['date_updated'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def subresource_uris(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAccessControlListInstance]: """ - :returns: The subresource_uris - :rtype: unicode + 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 self._properties['subresource_uris'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def uri(self): + 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: """ - :returns: The URI for this resource - :rtype: unicode + 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 """ - return self._properties['uri'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" - def fetch(self): + 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: """ - Fetch a IpAccessControlListInstance + 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: Fetched IpAccessControlListInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance + :returns: Page of IpAccessControlListInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return IpAccessControlListPage(self._version, response, self._solution) - def update(self, friendly_name): + async def get_page_async(self, target_url: str) -> IpAccessControlListPage: """ - Update the IpAccessControlListInstance + Asynchronously retrieve a specific page of IpAccessControlListInstance records from the API. + Request is executed immediately - :param unicode friendly_name: A human readable description of this resource + :param target_url: API-generated URL for the requested results page - :returns: Updated IpAccessControlListInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance + :returns: Page of IpAccessControlListInstance """ - return self._proxy.update(friendly_name, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return IpAccessControlListPage(self._version, response, self._solution) - def delete(self): + def get(self, sid: str) -> IpAccessControlListContext: """ - Deletes the IpAccessControlListInstance + Constructs a IpAccessControlListContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: A 34 character string that uniquely identifies the resource to udpate. """ - return self._proxy.delete() + return IpAccessControlListContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - @property - def ip_addresses(self): + def __call__(self, sid: str) -> IpAccessControlListContext: """ - Access the ip_addresses + Constructs a IpAccessControlListContext - :returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressList - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressList + :param sid: A 34 character string that uniquely identifies the resource to udpate. """ - return self._proxy.ip_addresses + return IpAccessControlListContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 index ccf6394bbe..ca2f82eacc 100644 --- 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 @@ -1,481 +1,724 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 IpAddressList(ListResource): - """ """ +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 - def __init__(self, version, account_sid, ip_access_control_list_sid): + @property + def _proxy(self) -> "IpAddressContext": """ - Initialize the IpAddressList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param ip_access_control_list_sid: The ip_access_control_list_sid + :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 - :returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressList - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressList + def delete(self) -> bool: """ - super(IpAddressList, self).__init__(version) + Deletes the IpAddressInstance - # 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 stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + return self._proxy.delete() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpAddressInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressInstance] + + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "IpAddressInstance": + """ + Fetch the IpAddressInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + return self._proxy.fetch() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + async def fetch_async(self) -> "IpAddressInstance": + """ + Asynchronous coroutine to fetch the IpAddressInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressInstance] + + :returns: The fetched IpAddressInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + 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": """ - Retrieve a single page of IpAddressInstance records from the API. - Request is executed immediately + Update the IpAddressInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :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: Page of IpAddressInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressPage + :returns: The updated IpAddressInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.update( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) - response = self._version.page( - 'GET', - self._uri, - params=params, + 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, ) - return IpAddressPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get_page(self, target_url): + :returns: Machine friendly representation """ - Retrieve a specific page of IpAddressInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param str target_url: API-generated URL for the requested results page - :returns: Page of IpAddressInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressPage +class IpAddressContext(InstanceContext): + + def __init__( + self, + version: Version, + account_sid: str, + ip_access_control_list_sid: str, + sid: str, + ): """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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 ) - return IpAddressPage(self._version, response, self._solution) + def delete(self) -> bool: + """ + Deletes the IpAddressInstance + - def create(self, friendly_name, ip_address): + :returns: True if delete succeeds, False otherwise """ - Create a new IpAddressInstance - :param unicode friendly_name: The friendly_name - :param unicode ip_address: The ip_address + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - :returns: Newly created IpAddressInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressInstance + async def delete_async(self) -> bool: """ - data = values.of({'FriendlyName': friendly_name, 'IpAddress': ip_address, }) + Asynchronous coroutine that deletes the IpAddressInstance - payload = self._version.create( - 'POST', - self._uri, - data=data, + + :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'], + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + sid=self._solution["sid"], ) - def get(self, sid): + async def fetch_async(self) -> IpAddressInstance: """ - Constructs a IpAddressContext + Asynchronous coroutine to fetch the IpAddressInstance - :param sid: The sid - :returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressContext - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressContext + :returns: The fetched IpAddressInstance """ - return IpAddressContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return IpAddressInstance( self._version, - account_sid=self._solution['account_sid'], - ip_access_control_list_sid=self._solution['ip_access_control_list_sid'], - sid=sid, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + sid=self._solution["sid"], ) - def __call__(self, 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: """ - Constructs a IpAddressContext + Update the IpAddressInstance - :param sid: The sid + :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: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressContext - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressContext + :returns: The updated IpAddressInstance """ - return IpAddressContext( + + 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, - account_sid=self._solution['account_sid'], - ip_access_control_list_sid=self._solution['ip_access_control_list_sid'], - sid=sid, + 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): + 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: """ - Provide a friendly representation + Asynchronous coroutine to update the IpAddressInstance - :returns: Machine friendly representation - :rtype: str + :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 '' + data = values.of( + { + "IpAddress": ip_address, + "FriendlyName": friendly_name, + "CidrPrefixLength": cidr_prefix_length, + } + ) + headers = values.of({}) -class IpAddressPage(Page): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, response, solution): - """ - Initialize the IpAddressPage + 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"], + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The account_sid - :param ip_access_control_list_sid: The ip_access_control_list_sid + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressPage - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressPage + :returns: Machine friendly representation """ - super(IpAddressPage, self).__init__(version, response) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Path Solution - self._solution = solution - def get_instance(self, payload): +class IpAddressPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> IpAddressInstance: """ Build an instance of IpAddressInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.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'], + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class IpAddressContext(InstanceContext): - """ """ +class IpAddressList(ListResource): - def __init__(self, version, account_sid, ip_access_control_list_sid, sid): + def __init__( + self, version: Version, account_sid: str, ip_access_control_list_sid: str + ): """ - Initialize the IpAddressContext + Initialize the IpAddressList - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param ip_access_control_list_sid: The ip_access_control_list_sid - :param sid: The sid + :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. - :returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressContext - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressContext """ - super(IpAddressContext, self).__init__(version) + super().__init__(version) # Path Solution self._solution = { - 'account_sid': account_sid, - 'ip_access_control_list_sid': ip_access_control_list_sid, - 'sid': sid, + "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/{sid}.json'.format(**self._solution) + self._uri = "/Accounts/{account_sid}/SIP/IpAccessControlLists/{ip_access_control_list_sid}/IpAddresses.json".format( + **self._solution + ) - def fetch(self): + def create( + self, + friendly_name: str, + ip_address: str, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> IpAddressInstance: """ - Fetch a 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: Fetched IpAddressInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressInstance + :returns: The created IpAddressInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], ) - def update(self, ip_address=values.unset, friendly_name=values.unset): + async def create_async( + self, + friendly_name: str, + ip_address: str, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> IpAddressInstance: """ - Update the IpAddressInstance + Asynchronously create the IpAddressInstance - :param unicode ip_address: The ip_address - :param unicode friendly_name: The friendly_name + :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: Updated IpAddressInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressInstance + :returns: The created IpAddressInstance """ - data = values.of({'IpAddress': ip_address, 'FriendlyName': friendly_name, }) - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], ) - def delete(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[IpAddressInstance]: """ - Deletes the 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. - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - def __repr__(self): + :returns: Generator that will yield up to limit results """ - Provide a friendly representation + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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. -class IpAddressInstance(InstanceResource): - """ """ + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - def __init__(self, version, payload, account_sid, ip_access_control_list_sid, - sid=None): + :returns: Generator that will yield up to limit results """ - Initialize the IpAddressInstance + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - :returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressInstance + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAddressInstance]: """ - super(IpAddressInstance, self).__init__(version) + Lists IpAddressInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'friendly_name': payload['friendly_name'], - 'ip_address': payload['ip_address'], - 'ip_access_control_list_sid': payload['ip_access_control_list_sid'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'uri': payload['uri'], - } + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - # Context - self._context = None - self._solution = { - 'account_sid': account_sid, - 'ip_access_control_list_sid': ip_access_control_list_sid, - 'sid': sid or self._properties['sid'], - } + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def _proxy(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAddressInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: IpAddressContext for this IpAddressInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressContext + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - 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 [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, ) - return self._context + ] - @property - def sid(self): + 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: """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + Retrieve a single page of IpAddressInstance records from the API. + Request is executed immediately - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_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 - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode + :returns: Page of IpAddressInstance """ - return self._properties['friendly_name'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def ip_address(self): - """ - :returns: The ip_address - :rtype: unicode - """ - return self._properties['ip_address'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def ip_access_control_list_sid(self): - """ - :returns: The ip_access_control_list_sid - :rtype: unicode - """ - return self._properties['ip_access_control_list_sid'] + headers["Accept"] = "application/json" - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpAddressPage(self._version, response, self._solution) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime + 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: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page of IpAddressInstance records from the API. + Request is executed immediately - @property - def uri(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The uri - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['uri'] + Retrieve a specific page of IpAddressInstance records from the API. + Request is executed immediately - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpAddressInstance """ - Fetch a IpAddressInstance + response = self._version.domain.twilio.request("GET", target_url) + return IpAddressPage(self._version, response, self._solution) - :returns: Fetched IpAddressInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressInstance + async def get_page_async(self, target_url: str) -> IpAddressPage: """ - return self._proxy.fetch() + 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 - def update(self, ip_address=values.unset, friendly_name=values.unset): + :returns: Page of IpAddressInstance """ - Update the IpAddressInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return IpAddressPage(self._version, response, self._solution) - :param unicode ip_address: The ip_address - :param unicode friendly_name: The friendly_name + def get(self, sid: str) -> IpAddressContext: + """ + Constructs a IpAddressContext - :returns: Updated IpAddressInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressInstance + :param sid: A 34 character string that identifies the IpAddress resource to update. """ - return self._proxy.update(ip_address=ip_address, friendly_name=friendly_name, ) + 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 delete(self): + def __call__(self, sid: str) -> IpAddressContext: """ - Deletes the IpAddressInstance + Constructs a IpAddressContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: A 34 character string that identifies the IpAddress resource to update. """ - return self._proxy.delete() + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/api/v2010/account/token.py b/twilio/rest/api/v2010/account/token.py index c0fa9a02e4..fa43360fb1 100644 --- a/twilio/rest/api/v2010/account/token.py +++ b/twilio/rest/api/v2010/account/token.py @@ -1,194 +1,146 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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.page import Page - - -class TokenList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the TokenList - - :param Version version: Version that contains the resource - :param account_sid: The unique sid that identifies this account - - :returns: twilio.rest.api.v2010.account.token.TokenList - :rtype: twilio.rest.api.v2010.account.token.TokenList - """ - super(TokenList, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Tokens.json'.format(**self._solution) +from twilio.base.version import Version - def create(self, ttl=values.unset): - """ - Create a new TokenInstance - - :param unicode ttl: The duration in seconds the credentials are valid - - :returns: Newly created TokenInstance - :rtype: twilio.rest.api.v2010.account.token.TokenInstance - """ - data = values.of({'Ttl': ttl, }) - payload = self._version.create( - 'POST', - self._uri, - data=data, +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") - return TokenInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + self._solution = { + "account_sid": account_sid, + } - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class TokenPage(Page): - """ """ +class TokenList(ListResource): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str): """ - Initialize the TokenPage + Initialize the TokenList - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The unique sid that identifies this account + :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. - :returns: twilio.rest.api.v2010.account.token.TokenPage - :rtype: twilio.rest.api.v2010.account.token.TokenPage """ - super(TokenPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Tokens.json".format(**self._solution) - def get_instance(self, payload): + def create(self, ttl: Union[int, object] = values.unset) -> TokenInstance: """ - Build an instance of TokenInstance + Create the TokenInstance - :param dict payload: Payload response from the API + :param ttl: The duration in seconds for which the generated credentials are valid. The default value is 86400 (24 hours). - :returns: twilio.rest.api.v2010.account.token.TokenInstance - :rtype: twilio.rest.api.v2010.account.token.TokenInstance + :returns: The created TokenInstance """ - return TokenInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - def __repr__(self): - """ - Provide a friendly representation + data = values.of( + { + "Ttl": ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" -class TokenInstance(InstanceResource): - """ """ + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - def __init__(self, version, payload, account_sid): - """ - Initialize the TokenInstance + return TokenInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - :returns: twilio.rest.api.v2010.account.token.TokenInstance - :rtype: twilio.rest.api.v2010.account.token.TokenInstance + async def create_async( + self, ttl: Union[int, object] = values.unset + ) -> TokenInstance: """ - super(TokenInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'ice_servers': payload['ice_servers'], - 'password': payload['password'], - 'ttl': payload['ttl'], - 'username': payload['username'], - } - - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + Asynchronously create the TokenInstance - @property - def account_sid(self): - """ - :returns: The unique sid that identifies this account - :rtype: unicode - """ - return self._properties['account_sid'] + :param ttl: The duration in seconds for which the generated credentials are valid. The default value is 86400 (24 hours). - @property - def date_created(self): - """ - :returns: The date this resource was created - :rtype: datetime + :returns: The created TokenInstance """ - return self._properties['date_created'] - @property - def date_updated(self): - """ - :returns: The date this resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + data = values.of( + { + "Ttl": ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def ice_servers(self): - """ - :returns: An array representing the ephemeral credentials - :rtype: unicode - """ - return self._properties['ice_servers'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def password(self): - """ - :returns: The temporary password used for authenticating - :rtype: unicode - """ - return self._properties['password'] + headers["Accept"] = "application/json" - @property - def ttl(self): - """ - :returns: The duration in seconds the credentials are valid - :rtype: unicode - """ - return self._properties['ttl'] + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def username(self): - """ - :returns: The temporary username that uniquely identifies a Token. - :rtype: unicode - """ - return self._properties['username'] + return TokenInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/api/v2010/account/transcription.py b/twilio/rest/api/v2010/account/transcription.py index 16d1f88b02..386ff9ee74 100644 --- a/twilio/rest/api/v2010/account/transcription.py +++ b/twilio/rest/api/v2010/account/transcription.py @@ -1,436 +1,504 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 TranscriptionList(ListResource): - """ """ +class TranscriptionInstance(InstanceResource): - def __init__(self, version, account_sid): - """ - Initialize the TranscriptionList + class Status(object): + IN_PROGRESS = "in-progress" + COMPLETED = "completed" + FAILED = "failed" - :param Version version: Version that contains the resource - :param account_sid: The unique sid that identifies this account + """ + :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 - :returns: twilio.rest.api.v2010.account.transcription.TranscriptionList - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionList + @property + def _proxy(self) -> "TranscriptionContext": """ - super(TranscriptionList, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Transcriptions.json'.format(**self._solution) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def stream(self, limit=None, page_size=None): + :returns: TranscriptionContext for this 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + if self._context is None: + self._context = TranscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.transcription.TranscriptionInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the TranscriptionInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists TranscriptionInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the TranscriptionInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.transcription.TranscriptionInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "TranscriptionInstance": """ - Retrieve a single page of TranscriptionInstance records from the API. - Request is executed immediately + Fetch the TranscriptionInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionPage + :returns: The fetched TranscriptionInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return TranscriptionPage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "TranscriptionInstance": """ - Retrieve a specific page of TranscriptionInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the TranscriptionInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionPage + :returns: The fetched TranscriptionInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return await self._proxy.fetch_async() - return TranscriptionPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a TranscriptionContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param sid: Fetch by unique transcription Sid - :returns: twilio.rest.api.v2010.account.transcription.TranscriptionContext - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionContext +class TranscriptionContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): """ - return TranscriptionContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + Initialize the TranscriptionContext - def __call__(self, sid): + :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. """ - Constructs a TranscriptionContext + super().__init__(version) - :param sid: Fetch by unique transcription Sid + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Transcriptions/{sid}.json".format( + **self._solution + ) - :returns: twilio.rest.api.v2010.account.transcription.TranscriptionContext - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionContext + def delete(self) -> bool: """ - return TranscriptionContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + Deletes the TranscriptionInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class TranscriptionPage(Page): - """ """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, response, solution): + async def delete_async(self) -> bool: """ - Initialize the TranscriptionPage + Asynchronous coroutine that deletes the TranscriptionInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The unique sid that identifies this account - :returns: twilio.rest.api.v2010.account.transcription.TranscriptionPage - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionPage + :returns: True if delete succeeds, False otherwise """ - super(TranscriptionPage, self).__init__(version, response) - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of TranscriptionInstance + headers = values.of({}) - :param dict payload: Payload response from the API + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.api.v2010.account.transcription.TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionInstance + def fetch(self) -> TranscriptionInstance: """ - return TranscriptionInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + Fetch the TranscriptionInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: The fetched TranscriptionInstance """ - return '' + headers = values.of({}) -class TranscriptionContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, account_sid, sid): - """ - Initialize the TranscriptionContext + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param sid: Fetch by unique transcription Sid + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.api.v2010.account.transcription.TranscriptionContext - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionContext + async def fetch_async(self) -> TranscriptionInstance: """ - super(TranscriptionContext, self).__init__(version) + Asynchronous coroutine to fetch the TranscriptionInstance - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/Transcriptions/{sid}.json'.format(**self._solution) - def fetch(self): + :returns: The fetched TranscriptionInstance """ - Fetch a TranscriptionInstance - :returns: Fetched TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionInstance - """ - params = values.of({}) + headers = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def delete(self): + def __repr__(self) -> str: """ - Deletes the TranscriptionInstance + Provide a friendly representation - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TranscriptionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TranscriptionInstance: """ - return self._version.delete('delete', self._uri) + Build an instance of TranscriptionInstance - def __repr__(self): + :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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - + return "" -class TranscriptionInstance(InstanceResource): - """ """ - class Status(object): - IN_PROGRESS = "in-progress" - COMPLETED = "completed" - FAILED = "failed" +class TranscriptionList(ListResource): - def __init__(self, version, payload, account_sid, sid=None): - """ - Initialize the TranscriptionInstance - - :returns: twilio.rest.api.v2010.account.transcription.TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionInstance - """ - super(TranscriptionInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'api_version': payload['api_version'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'duration': payload['duration'], - 'price': deserialize.decimal(payload['price']), - 'price_unit': payload['price_unit'], - 'recording_sid': payload['recording_sid'], - 'sid': payload['sid'], - 'status': payload['status'], - 'transcription_text': payload['transcription_text'], - 'type': payload['type'], - 'uri': payload['uri'], - } + def __init__(self, version: Version, account_sid: str): + """ + Initialize the TranscriptionList - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } + :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. - @property - def _proxy(self): """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + super().__init__(version) - :returns: TranscriptionContext for this TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionContext - """ - if self._context is None: - self._context = TranscriptionContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Transcriptions.json".format( + **self._solution + ) - @property - def account_sid(self): - """ - :returns: The unique sid that identifies this account - :rtype: unicode + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TranscriptionInstance]: """ - return self._properties['account_sid'] + 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. - @property - def api_version(self): - """ - :returns: The api_version - :rtype: unicode - """ - return self._properties['api_version'] + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - @property - def date_created(self): - """ - :returns: The date this resource was created - :rtype: datetime + :returns: Generator that will yield up to limit results """ - return self._properties['date_created'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def date_updated(self): - """ - :returns: The date this resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + return self._version.stream(page, limits["limit"]) - @property - def duration(self): - """ - :returns: The duration of the transcribed audio, in seconds. - :rtype: unicode + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TranscriptionInstance]: """ - return self._properties['duration'] + 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. - @property - def price(self): - """ - :returns: The charge for this transcription - :rtype: unicode - """ - return self._properties['price'] + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - @property - def price_unit(self): - """ - :returns: The currency in which Price is measured - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['price_unit'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def recording_sid(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TranscriptionInstance]: """ - :returns: The string that uniquely identifies the recording - :rtype: unicode + 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 self._properties['recording_sid'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TranscriptionInstance]: """ - :returns: A string that uniquely identifies this transcription - :rtype: unicode + 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 self._properties['sid'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def status(self): + 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: """ - :returns: The status of the transcription - :rtype: TranscriptionInstance.Status + 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 """ - return self._properties['status'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def transcription_text(self): + headers = values.of({"Content-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: """ - :returns: The text content of the transcription. - :rtype: unicode + 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 """ - return self._properties['transcription_text'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def type(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The type - :rtype: unicode + 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 """ - return self._properties['type'] + response = self._version.domain.twilio.request("GET", target_url) + return TranscriptionPage(self._version, response, self._solution) - @property - def uri(self): + async def get_page_async(self, target_url: str) -> TranscriptionPage: """ - :returns: The URI for this resource - :rtype: unicode + 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 """ - return self._properties['uri'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return TranscriptionPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> TranscriptionContext: """ - Fetch a TranscriptionInstance + Constructs a TranscriptionContext - :returns: Fetched TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionInstance + :param sid: The Twilio-provided string that uniquely identifies the Transcription resource to fetch. """ - return self._proxy.fetch() + return TranscriptionContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def delete(self): + def __call__(self, sid: str) -> TranscriptionContext: """ - Deletes the TranscriptionInstance + Constructs a TranscriptionContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the Transcription resource to fetch. """ - return self._proxy.delete() + return TranscriptionContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/api/v2010/account/usage/__init__.py b/twilio/rest/api/v2010/account/usage/__init__.py index 78a3efae4f..8fe80f64ba 100644 --- a/twilio/rest/api/v2010/account/usage/__init__.py +++ b/twilio/rest/api/v2010/account/usage/__init__.py @@ -1,135 +1,74 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base.instance_resource import InstanceResource +from typing import Optional + + from twilio.base.list_resource import ListResource -from twilio.base.page import Page +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, account_sid): + def __init__(self, version: Version, account_sid: str): """ Initialize the UsageList - :param Version version: Version that contains the resource - :param account_sid: A 34 character string that uniquely identifies this resource. + :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. - :returns: twilio.rest.api.v2010.account.usage.UsageList - :rtype: twilio.rest.api.v2010.account.usage.UsageList """ - super(UsageList, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'account_sid': account_sid, } + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage.json".format(**self._solution) - # Components - self._records = None - self._triggers = None + self._records: Optional[RecordList] = None + self._triggers: Optional[TriggerList] = None @property - def records(self): + def records(self) -> RecordList: """ Access the records - - :returns: twilio.rest.api.v2010.account.usage.record.RecordList - :rtype: twilio.rest.api.v2010.account.usage.record.RecordList """ if self._records is None: - self._records = RecordList(self._version, account_sid=self._solution['account_sid'], ) + self._records = RecordList( + self._version, account_sid=self._solution["account_sid"] + ) return self._records @property - def triggers(self): + def triggers(self) -> TriggerList: """ Access the triggers - - :returns: twilio.rest.api.v2010.account.usage.trigger.TriggerList - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerList """ if self._triggers is None: - self._triggers = TriggerList(self._version, account_sid=self._solution['account_sid'], ) + self._triggers = TriggerList( + self._version, account_sid=self._solution["account_sid"] + ) return self._triggers - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class UsagePage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the UsagePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.usage.UsagePage - :rtype: twilio.rest.api.v2010.account.usage.UsagePage - """ - super(UsagePage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of UsageInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.usage.UsageInstance - :rtype: twilio.rest.api.v2010.account.usage.UsageInstance - """ - return UsageInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class UsageInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid): - """ - Initialize the UsageInstance - - :returns: twilio.rest.api.v2010.account.usage.UsageInstance - :rtype: twilio.rest.api.v2010.account.usage.UsageInstance - """ - super(UsageInstance, self).__init__(version) - - # Context - self._context = None - self._solution = {'account_sid': account_sid, } - - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/api/v2010/account/usage/record/__init__.py b/twilio/rest/api/v2010/account/usage/record/__init__.py index 13476fd05a..d60bde9b6b 100644 --- a/twilio/rest/api/v2010/account/usage/record/__init__.py +++ b/twilio/rest/api/v2010/account/usage/record/__init__.py @@ -1,16 +1,24 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 @@ -22,318 +30,104 @@ from twilio.rest.api.v2010.account.usage.record.yesterday import YesterdayList -class RecordList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the RecordList - - :param Version version: Version that contains the resource - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.usage.record.RecordList - :rtype: twilio.rest.api.v2010.account.usage.record.RecordList - """ - super(RecordList, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Usage/Records.json'.format(**self._solution) - - # Components - self._all_time = None - self._daily = None - self._last_month = None - self._monthly = None - self._this_month = None - self._today = None - self._yearly = None - self._yesterday = None - - def stream(self, category=values.unset, start_date=values.unset, - end_date=values.unset, limit=None, page_size=None): - """ - 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: Only include usage of a given category - :param date start_date: Filter by start date - :param date end_date: Filter by end date - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.usage.record.RecordInstance] - """ - limits = self._version.read_limits(limit, page_size) +class RecordInstance(InstanceResource): - page = self.page( - category=category, - start_date=start_date, - end_date=end_date, - page_size=limits['page_size'], + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, limit=None, page_size=None): - """ - 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: Only include usage of a given category - :param date start_date: Filter by start date - :param date end_date: Filter by end date - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.usage.record.RecordInstance] - """ - return list(self.stream( - category=category, - start_date=start_date, - end_date=end_date, - limit=limit, - page_size=page_size, - )) - - def page(self, category=values.unset, start_date=values.unset, - end_date=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of RecordInstance records from the API. - Request is executed immediately - - :param RecordInstance.Category category: Only include usage of a given category - :param date start_date: Filter by start date - :param date end_date: Filter by end date - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of RecordInstance - :rtype: twilio.rest.api.v2010.account.usage.record.RecordPage - """ - params = values.of({ - 'Category': category, - 'StartDate': serialize.iso8601_date(start_date), - 'EndDate': serialize.iso8601_date(end_date), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" ) - - return RecordPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of RecordInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of RecordInstance - :rtype: twilio.rest.api.v2010.account.usage.record.RecordPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" ) - - return RecordPage(self._version, response, self._solution) - - @property - def all_time(self): - """ - Access the all_time - - :returns: twilio.rest.api.v2010.account.usage.record.all_time.AllTimeList - :rtype: twilio.rest.api.v2010.account.usage.record.all_time.AllTimeList - """ - 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): - """ - Access the daily - - :returns: twilio.rest.api.v2010.account.usage.record.daily.DailyList - :rtype: twilio.rest.api.v2010.account.usage.record.daily.DailyList - """ - if self._daily is None: - self._daily = DailyList(self._version, account_sid=self._solution['account_sid'], ) - return self._daily - - @property - def last_month(self): - """ - Access the last_month - - :returns: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthList - :rtype: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthList - """ - 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): - """ - Access the monthly - - :returns: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyList - :rtype: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyList - """ - if self._monthly is None: - self._monthly = MonthlyList(self._version, account_sid=self._solution['account_sid'], ) - return self._monthly - - @property - def this_month(self): - """ - Access the this_month - - :returns: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthList - :rtype: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthList - """ - 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): - """ - Access the today - - :returns: twilio.rest.api.v2010.account.usage.record.today.TodayList - :rtype: twilio.rest.api.v2010.account.usage.record.today.TodayList - """ - if self._today is None: - self._today = TodayList(self._version, account_sid=self._solution['account_sid'], ) - return self._today - - @property - def yearly(self): - """ - Access the yearly - - :returns: twilio.rest.api.v2010.account.usage.record.yearly.YearlyList - :rtype: twilio.rest.api.v2010.account.usage.record.yearly.YearlyList - """ - if self._yearly is None: - self._yearly = YearlyList(self._version, account_sid=self._solution['account_sid'], ) - return self._yearly - - @property - def yesterday(self): - """ - Access the yesterday - - :returns: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayList - :rtype: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayList - """ - if self._yesterday is None: - self._yesterday = YesterdayList(self._version, account_sid=self._solution['account_sid'], ) - return self._yesterday - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class RecordPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the RecordPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.usage.record.RecordPage - :rtype: twilio.rest.api.v2010.account.usage.record.RecordPage - """ - super(RecordPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of RecordInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.usage.record.RecordInstance - :rtype: twilio.rest.api.v2010.account.usage.record.RecordInstance - """ - return RecordInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class RecordInstance(InstanceResource): - """ """ - - class Category(object): + 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" @@ -342,6 +136,40 @@ class Category(object): 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" @@ -356,55 +184,155 @@ class Category(object): 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_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - 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_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = "marketplace-infogroup-dataaxle-bizinfo" + 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_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = "marketplace-keen-io-contact-center-analytics" + 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_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_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_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_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_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + 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_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" + 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" @@ -415,26 +343,59 @@ class Category(object): 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" - PCHAT_MESSAGES = "pchat-messages" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = "peer-to-peer-rooms-participant-minutes" + 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" @@ -445,28 +406,51 @@ class Category(object): 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" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" 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_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + 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" @@ -485,31 +469,157 @@ class Category(object): 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_AUDIO_TRACE = "voice-insights-audio-trace" - VOICE_INSIGHTS_CARRIER_CALLS = "voice-insights-carrier-calls" + 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_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" @@ -518,16 +628,30 @@ class Category(object): 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_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_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" @@ -538,157 +662,655 @@ class Category(object): 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_VOICE = "wireless-usage-voice" 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") - def __init__(self, version, payload, account_sid): - """ - Initialize the RecordInstance - - :returns: twilio.rest.api.v2010.account.usage.record.RecordInstance - :rtype: twilio.rest.api.v2010.account.usage.record.RecordInstance - """ - super(RecordInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'api_version': payload['api_version'], - 'category': payload['category'], - 'count': payload['count'], - 'count_unit': payload['count_unit'], - 'description': payload['description'], - 'end_date': deserialize.iso8601_date(payload['end_date']), - 'price': deserialize.decimal(payload['price']), - 'price_unit': payload['price_unit'], - 'start_date': deserialize.iso8601_date(payload['start_date']), - 'subresource_uris': payload['subresource_uris'], - 'uri': payload['uri'], - 'usage': payload['usage'], - 'usage_unit': payload['usage_unit'], + self._solution = { + "account_sid": account_sid, } - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + def __repr__(self) -> str: + """ + Provide a friendly representation - @property - def account_sid(self): + :returns: Machine friendly representation """ - :returns: The Account that accrued the usage - :rtype: unicode + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RecordPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RecordInstance: """ - return self._properties['account_sid'] + Build an instance of RecordInstance - @property - def api_version(self): + :param payload: Payload response from the API """ - :returns: The api_version - :rtype: unicode + return RecordInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: """ - return self._properties['api_version'] + Provide a friendly representation - @property - def category(self): + :returns: Machine friendly representation """ - :returns: The category of usage - :rtype: RecordInstance.Category + return "" + + +class RecordList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - return self._properties['category'] + 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. - @property - def count(self): """ - :returns: The number of usage events (e.g. the number of calls). - :rtype: unicode + 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]: """ - return self._properties['count'] + 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. - @property - def count_unit(self): + :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 """ - :returns: The unit in which `Count` is measured - :rtype: unicode + 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]: """ - return self._properties['count_unit'] + 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. - @property - def description(self): + :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: """ - :returns: A human-readable description of the usage category. - :rtype: unicode + 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 """ - return self._properties['description'] + 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 end_date(self): + def all_time(self) -> AllTimeList: """ - :returns: The last date usage is included in this record - :rtype: date + Access the all_time """ - return self._properties['end_date'] + if self._all_time is None: + self._all_time = AllTimeList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._all_time @property - def price(self): + def daily(self) -> DailyList: """ - :returns: The total price of the usage - :rtype: unicode + Access the daily """ - return self._properties['price'] + if self._daily is None: + self._daily = DailyList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._daily @property - def price_unit(self): + def last_month(self) -> LastMonthList: """ - :returns: The currency in which `Price` is measured - :rtype: unicode + Access the last_month """ - return self._properties['price_unit'] + if self._last_month is None: + self._last_month = LastMonthList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._last_month @property - def start_date(self): + def monthly(self) -> MonthlyList: """ - :returns: The first date usage is included in this record - :rtype: date + Access the monthly """ - return self._properties['start_date'] + if self._monthly is None: + self._monthly = MonthlyList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._monthly @property - def subresource_uris(self): + def this_month(self) -> ThisMonthList: """ - :returns: Subresources Uris for this UsageRecord - :rtype: unicode + Access the this_month """ - return self._properties['subresource_uris'] + if self._this_month is None: + self._this_month = ThisMonthList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._this_month @property - def uri(self): + def today(self) -> TodayList: """ - :returns: The URI for this resource - :rtype: unicode + Access the today """ - return self._properties['uri'] + if self._today is None: + self._today = TodayList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._today @property - def usage(self): + def yearly(self) -> YearlyList: """ - :returns: The amount of usage - :rtype: unicode + Access the yearly """ - return self._properties['usage'] + if self._yearly is None: + self._yearly = YearlyList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._yearly @property - def usage_unit(self): + def yesterday(self) -> YesterdayList: """ - :returns: The units in which `Usage` is measured - :rtype: unicode + Access the yesterday """ - return self._properties['usage_unit'] + if self._yesterday is None: + self._yesterday = YesterdayList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._yesterday - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/api/v2010/account/usage/record/all_time.py b/twilio/rest/api/v2010/account/usage/record/all_time.py index e99af745c7..991f4a0b70 100644 --- a/twilio/rest/api/v2010/account/usage/record/all_time.py +++ b/twilio/rest/api/v2010/account/usage/record/all_time.py @@ -1,225 +1,125 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 AllTimeList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the AllTimeList - - :param Version version: Version that contains the resource - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.usage.record.all_time.AllTimeList - :rtype: twilio.rest.api.v2010.account.usage.record.all_time.AllTimeList - """ - super(AllTimeList, self).__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=values.unset, start_date=values.unset, - end_date=values.unset, limit=None, page_size=None): - """ - 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 category - :param date start_date: The start_date - :param date end_date: The end_date - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.usage.record.all_time.AllTimeInstance] - """ - limits = self._version.read_limits(limit, page_size) +class AllTimeInstance(InstanceResource): - page = self.page( - category=category, - start_date=start_date, - end_date=end_date, - page_size=limits['page_size'], + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, limit=None, page_size=None): - """ - 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 category - :param date start_date: The start_date - :param date end_date: The end_date - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.usage.record.all_time.AllTimeInstance] - """ - return list(self.stream( - category=category, - start_date=start_date, - end_date=end_date, - limit=limit, - page_size=page_size, - )) - - def page(self, category=values.unset, start_date=values.unset, - end_date=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of AllTimeInstance records from the API. - Request is executed immediately - - :param AllTimeInstance.Category category: The category - :param date start_date: The start_date - :param date end_date: The end_date - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of AllTimeInstance - :rtype: twilio.rest.api.v2010.account.usage.record.all_time.AllTimePage - """ - params = values.of({ - 'Category': category, - 'StartDate': serialize.iso8601_date(start_date), - 'EndDate': serialize.iso8601_date(end_date), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" ) - - return AllTimePage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of AllTimeInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of AllTimeInstance - :rtype: twilio.rest.api.v2010.account.usage.record.all_time.AllTimePage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" ) - - return AllTimePage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class AllTimePage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the AllTimePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.usage.record.all_time.AllTimePage - :rtype: twilio.rest.api.v2010.account.usage.record.all_time.AllTimePage - """ - super(AllTimePage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of AllTimeInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.usage.record.all_time.AllTimeInstance - :rtype: twilio.rest.api.v2010.account.usage.record.all_time.AllTimeInstance - """ - return AllTimeInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class AllTimeInstance(InstanceResource): - """ """ - - class Category(object): + 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" @@ -228,6 +128,40 @@ class Category(object): 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" @@ -242,55 +176,155 @@ class Category(object): 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_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - 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_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = "marketplace-infogroup-dataaxle-bizinfo" + 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_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = "marketplace-keen-io-contact-center-analytics" + 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_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_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_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_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_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + 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_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" + 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" @@ -301,26 +335,59 @@ class Category(object): 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" - PCHAT_MESSAGES = "pchat-messages" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = "peer-to-peer-rooms-participant-minutes" + 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" @@ -331,28 +398,51 @@ class Category(object): 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" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" 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_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + 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" @@ -371,31 +461,157 @@ class Category(object): 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_AUDIO_TRACE = "voice-insights-audio-trace" - VOICE_INSIGHTS_CARRIER_CALLS = "voice-insights-carrier-calls" + 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_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" @@ -404,16 +620,30 @@ class Category(object): 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_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_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" @@ -424,157 +654,558 @@ class Category(object): 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_VOICE = "wireless-usage-voice" 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" - def __init__(self, version, payload, account_sid): - """ - Initialize the AllTimeInstance + """ + :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. + """ - :returns: twilio.rest.api.v2010.account.usage.record.all_time.AllTimeInstance - :rtype: twilio.rest.api.v2010.account.usage.record.all_time.AllTimeInstance - """ - super(AllTimeInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'api_version': payload['api_version'], - 'category': payload['category'], - 'count': payload['count'], - 'count_unit': payload['count_unit'], - 'description': payload['description'], - 'end_date': deserialize.iso8601_date(payload['end_date']), - 'price': deserialize.decimal(payload['price']), - 'price_unit': payload['price_unit'], - 'start_date': deserialize.iso8601_date(payload['start_date']), - 'subresource_uris': payload['subresource_uris'], - 'uri': payload['uri'], - 'usage': payload['usage'], - 'usage_unit': payload['usage_unit'], - } + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + 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") - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + self._solution = { + "account_sid": account_sid, + } - @property - def api_version(self): - """ - :returns: The api_version - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['api_version'] + Provide a friendly representation - @property - def category(self): - """ - :returns: The category - :rtype: AllTimeInstance.Category + :returns: Machine friendly representation """ - return self._properties['category'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - @property - def count(self): +class AllTimePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AllTimeInstance: """ - :returns: The count - :rtype: unicode + Build an instance of AllTimeInstance + + :param payload: Payload response from the API """ - return self._properties['count'] + return AllTimeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def count_unit(self): + def __repr__(self) -> str: """ - :returns: The count_unit - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['count_unit'] + return "" - @property - def description(self): + +class AllTimeList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - :returns: The description - :rtype: unicode + 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. + """ - return self._properties['description'] + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records/AllTime.json".format( + **self._solution + ) - @property - def end_date(self): + 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]: """ - :returns: The end_date - :rtype: date + 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 """ - return self._properties['end_date'] + 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"], + ) - @property - def price(self): + 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]: """ - :returns: The price - :rtype: unicode + 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 """ - return self._properties['price'] + 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"]) - @property - def price_unit(self): + 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]: """ - :returns: The price_unit - :rtype: unicode + 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 self._properties['price_unit'] + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) - @property - def start_date(self): + 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]: """ - :returns: The start_date - :rtype: date + 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 self._properties['start_date'] + 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, + ) + ] - @property - def subresource_uris(self): + 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: """ - :returns: The subresource_uris - :rtype: unicode + 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 """ - return self._properties['subresource_uris'] + 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, + } + ) - @property - def uri(self): + headers = values.of({"Content-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: """ - :returns: The uri - :rtype: unicode + 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 """ - return self._properties['uri'] + 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"}) - @property - def usage(self): + 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: """ - :returns: The usage - :rtype: unicode + 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 """ - return self._properties['usage'] + response = self._version.domain.twilio.request("GET", target_url) + return AllTimePage(self._version, response, self._solution) - @property - def usage_unit(self): + async def get_page_async(self, target_url: str) -> AllTimePage: """ - :returns: The usage_unit - :rtype: unicode + 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 """ - return self._properties['usage_unit'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return AllTimePage(self._version, response, self._solution) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/api/v2010/account/usage/record/daily.py b/twilio/rest/api/v2010/account/usage/record/daily.py index 4bc83ac887..e89c75cb39 100644 --- a/twilio/rest/api/v2010/account/usage/record/daily.py +++ b/twilio/rest/api/v2010/account/usage/record/daily.py @@ -1,225 +1,125 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 DailyList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the DailyList - - :param Version version: Version that contains the resource - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.usage.record.daily.DailyList - :rtype: twilio.rest.api.v2010.account.usage.record.daily.DailyList - """ - super(DailyList, self).__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=values.unset, start_date=values.unset, - end_date=values.unset, limit=None, page_size=None): - """ - 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 category - :param date start_date: The start_date - :param date end_date: The end_date - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.usage.record.daily.DailyInstance] - """ - limits = self._version.read_limits(limit, page_size) +class DailyInstance(InstanceResource): - page = self.page( - category=category, - start_date=start_date, - end_date=end_date, - page_size=limits['page_size'], + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, limit=None, page_size=None): - """ - 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 category - :param date start_date: The start_date - :param date end_date: The end_date - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.usage.record.daily.DailyInstance] - """ - return list(self.stream( - category=category, - start_date=start_date, - end_date=end_date, - limit=limit, - page_size=page_size, - )) - - def page(self, category=values.unset, start_date=values.unset, - end_date=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of DailyInstance records from the API. - Request is executed immediately - - :param DailyInstance.Category category: The category - :param date start_date: The start_date - :param date end_date: The end_date - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of DailyInstance - :rtype: twilio.rest.api.v2010.account.usage.record.daily.DailyPage - """ - params = values.of({ - 'Category': category, - 'StartDate': serialize.iso8601_date(start_date), - 'EndDate': serialize.iso8601_date(end_date), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" ) - - return DailyPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of DailyInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of DailyInstance - :rtype: twilio.rest.api.v2010.account.usage.record.daily.DailyPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" ) - - return DailyPage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class DailyPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the DailyPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.usage.record.daily.DailyPage - :rtype: twilio.rest.api.v2010.account.usage.record.daily.DailyPage - """ - super(DailyPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of DailyInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.usage.record.daily.DailyInstance - :rtype: twilio.rest.api.v2010.account.usage.record.daily.DailyInstance - """ - return DailyInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class DailyInstance(InstanceResource): - """ """ - - class Category(object): + 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" @@ -228,6 +128,40 @@ class Category(object): 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" @@ -242,55 +176,155 @@ class Category(object): 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_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - 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_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = "marketplace-infogroup-dataaxle-bizinfo" + 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_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = "marketplace-keen-io-contact-center-analytics" + 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_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_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_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_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_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + 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_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" + 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" @@ -301,26 +335,59 @@ class Category(object): 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" - PCHAT_MESSAGES = "pchat-messages" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = "peer-to-peer-rooms-participant-minutes" + 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" @@ -331,28 +398,51 @@ class Category(object): 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" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" 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_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + 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" @@ -371,31 +461,157 @@ class Category(object): 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_AUDIO_TRACE = "voice-insights-audio-trace" - VOICE_INSIGHTS_CARRIER_CALLS = "voice-insights-carrier-calls" + 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_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" @@ -404,16 +620,30 @@ class Category(object): 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_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_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" @@ -424,157 +654,558 @@ class Category(object): 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_VOICE = "wireless-usage-voice" 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" - def __init__(self, version, payload, account_sid): - """ - Initialize the DailyInstance + """ + :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. + """ - :returns: twilio.rest.api.v2010.account.usage.record.daily.DailyInstance - :rtype: twilio.rest.api.v2010.account.usage.record.daily.DailyInstance - """ - super(DailyInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'api_version': payload['api_version'], - 'category': payload['category'], - 'count': payload['count'], - 'count_unit': payload['count_unit'], - 'description': payload['description'], - 'end_date': deserialize.iso8601_date(payload['end_date']), - 'price': deserialize.decimal(payload['price']), - 'price_unit': payload['price_unit'], - 'start_date': deserialize.iso8601_date(payload['start_date']), - 'subresource_uris': payload['subresource_uris'], - 'uri': payload['uri'], - 'usage': payload['usage'], - 'usage_unit': payload['usage_unit'], - } + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + 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") - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + self._solution = { + "account_sid": account_sid, + } - @property - def api_version(self): - """ - :returns: The api_version - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['api_version'] + Provide a friendly representation - @property - def category(self): - """ - :returns: The category - :rtype: DailyInstance.Category + :returns: Machine friendly representation """ - return self._properties['category'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - @property - def count(self): +class DailyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DailyInstance: """ - :returns: The count - :rtype: unicode + Build an instance of DailyInstance + + :param payload: Payload response from the API """ - return self._properties['count'] + return DailyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def count_unit(self): + def __repr__(self) -> str: """ - :returns: The count_unit - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['count_unit'] + return "" - @property - def description(self): + +class DailyList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - :returns: The description - :rtype: unicode + 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. + """ - return self._properties['description'] + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records/Daily.json".format( + **self._solution + ) - @property - def end_date(self): + 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]: """ - :returns: The end_date - :rtype: date + 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 """ - return self._properties['end_date'] + 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"], + ) - @property - def price(self): + 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]: """ - :returns: The price - :rtype: unicode + 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 """ - return self._properties['price'] + 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"]) - @property - def price_unit(self): + 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]: """ - :returns: The price_unit - :rtype: unicode + 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 self._properties['price_unit'] + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) - @property - def start_date(self): + 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]: """ - :returns: The start_date - :rtype: date + 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 self._properties['start_date'] + 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, + ) + ] - @property - def subresource_uris(self): + 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: """ - :returns: The subresource_uris - :rtype: unicode + 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 """ - return self._properties['subresource_uris'] + 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, + } + ) - @property - def uri(self): + headers = values.of({"Content-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: """ - :returns: The uri - :rtype: unicode + 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 """ - return self._properties['uri'] + 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"}) - @property - def usage(self): + 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: """ - :returns: The usage - :rtype: unicode + 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 """ - return self._properties['usage'] + response = self._version.domain.twilio.request("GET", target_url) + return DailyPage(self._version, response, self._solution) - @property - def usage_unit(self): + async def get_page_async(self, target_url: str) -> DailyPage: """ - :returns: The usage_unit - :rtype: unicode + 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 """ - return self._properties['usage_unit'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return DailyPage(self._version, response, self._solution) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/api/v2010/account/usage/record/last_month.py b/twilio/rest/api/v2010/account/usage/record/last_month.py index 5bfc5aa4ce..4057283e4a 100644 --- a/twilio/rest/api/v2010/account/usage/record/last_month.py +++ b/twilio/rest/api/v2010/account/usage/record/last_month.py @@ -1,225 +1,125 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 LastMonthList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the LastMonthList - - :param Version version: Version that contains the resource - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthList - :rtype: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthList - """ - super(LastMonthList, self).__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=values.unset, start_date=values.unset, - end_date=values.unset, limit=None, page_size=None): - """ - 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 category - :param date start_date: The start_date - :param date end_date: The end_date - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.usage.record.last_month.LastMonthInstance] - """ - limits = self._version.read_limits(limit, page_size) +class LastMonthInstance(InstanceResource): - page = self.page( - category=category, - start_date=start_date, - end_date=end_date, - page_size=limits['page_size'], + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, limit=None, page_size=None): - """ - 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 category - :param date start_date: The start_date - :param date end_date: The end_date - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.usage.record.last_month.LastMonthInstance] - """ - return list(self.stream( - category=category, - start_date=start_date, - end_date=end_date, - limit=limit, - page_size=page_size, - )) - - def page(self, category=values.unset, start_date=values.unset, - end_date=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of LastMonthInstance records from the API. - Request is executed immediately - - :param LastMonthInstance.Category category: The category - :param date start_date: The start_date - :param date end_date: The end_date - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of LastMonthInstance - :rtype: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthPage - """ - params = values.of({ - 'Category': category, - 'StartDate': serialize.iso8601_date(start_date), - 'EndDate': serialize.iso8601_date(end_date), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" ) - - return LastMonthPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of LastMonthInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of LastMonthInstance - :rtype: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" ) - - return LastMonthPage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class LastMonthPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the LastMonthPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthPage - :rtype: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthPage - """ - super(LastMonthPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of LastMonthInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthInstance - :rtype: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthInstance - """ - return LastMonthInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class LastMonthInstance(InstanceResource): - """ """ - - class Category(object): + 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" @@ -228,6 +128,40 @@ class Category(object): 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" @@ -242,55 +176,155 @@ class Category(object): 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_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - 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_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = "marketplace-infogroup-dataaxle-bizinfo" + 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_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = "marketplace-keen-io-contact-center-analytics" + 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_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_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_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_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_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + 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_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" + 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" @@ -301,26 +335,59 @@ class Category(object): 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" - PCHAT_MESSAGES = "pchat-messages" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = "peer-to-peer-rooms-participant-minutes" + 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" @@ -331,28 +398,51 @@ class Category(object): 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" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" 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_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + 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" @@ -371,31 +461,157 @@ class Category(object): 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_AUDIO_TRACE = "voice-insights-audio-trace" - VOICE_INSIGHTS_CARRIER_CALLS = "voice-insights-carrier-calls" + 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_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" @@ -404,16 +620,30 @@ class Category(object): 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_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_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" @@ -424,157 +654,558 @@ class Category(object): 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_VOICE = "wireless-usage-voice" 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" - def __init__(self, version, payload, account_sid): - """ - Initialize the LastMonthInstance + """ + :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. + """ - :returns: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthInstance - :rtype: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthInstance - """ - super(LastMonthInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'api_version': payload['api_version'], - 'category': payload['category'], - 'count': payload['count'], - 'count_unit': payload['count_unit'], - 'description': payload['description'], - 'end_date': deserialize.iso8601_date(payload['end_date']), - 'price': deserialize.decimal(payload['price']), - 'price_unit': payload['price_unit'], - 'start_date': deserialize.iso8601_date(payload['start_date']), - 'subresource_uris': payload['subresource_uris'], - 'uri': payload['uri'], - 'usage': payload['usage'], - 'usage_unit': payload['usage_unit'], - } + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + 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") - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + self._solution = { + "account_sid": account_sid, + } - @property - def api_version(self): - """ - :returns: The api_version - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['api_version'] + Provide a friendly representation - @property - def category(self): - """ - :returns: The category - :rtype: LastMonthInstance.Category + :returns: Machine friendly representation """ - return self._properties['category'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - @property - def count(self): +class LastMonthPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> LastMonthInstance: """ - :returns: The count - :rtype: unicode + Build an instance of LastMonthInstance + + :param payload: Payload response from the API """ - return self._properties['count'] + return LastMonthInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def count_unit(self): + def __repr__(self) -> str: """ - :returns: The count_unit - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['count_unit'] + return "" - @property - def description(self): + +class LastMonthList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - :returns: The description - :rtype: unicode + 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. + """ - return self._properties['description'] + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records/LastMonth.json".format( + **self._solution + ) - @property - def end_date(self): + 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]: """ - :returns: The end_date - :rtype: date + 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 """ - return self._properties['end_date'] + 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"], + ) - @property - def price(self): + 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]: """ - :returns: The price - :rtype: unicode + 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 """ - return self._properties['price'] + 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"]) - @property - def price_unit(self): + 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]: """ - :returns: The price_unit - :rtype: unicode + 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 self._properties['price_unit'] + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) - @property - def start_date(self): + 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]: """ - :returns: The start_date - :rtype: date + 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 self._properties['start_date'] + 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, + ) + ] - @property - def subresource_uris(self): + 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: """ - :returns: The subresource_uris - :rtype: unicode + 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 """ - return self._properties['subresource_uris'] + 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, + } + ) - @property - def uri(self): + headers = values.of({"Content-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: """ - :returns: The uri - :rtype: unicode + 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 """ - return self._properties['uri'] + 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"}) - @property - def usage(self): + 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: """ - :returns: The usage - :rtype: unicode + 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 """ - return self._properties['usage'] + response = self._version.domain.twilio.request("GET", target_url) + return LastMonthPage(self._version, response, self._solution) - @property - def usage_unit(self): + async def get_page_async(self, target_url: str) -> LastMonthPage: """ - :returns: The usage_unit - :rtype: unicode + 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 """ - return self._properties['usage_unit'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return LastMonthPage(self._version, response, self._solution) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/api/v2010/account/usage/record/monthly.py b/twilio/rest/api/v2010/account/usage/record/monthly.py index c6a48bf863..117db692bf 100644 --- a/twilio/rest/api/v2010/account/usage/record/monthly.py +++ b/twilio/rest/api/v2010/account/usage/record/monthly.py @@ -1,225 +1,125 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 MonthlyList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the MonthlyList - - :param Version version: Version that contains the resource - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyList - :rtype: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyList - """ - super(MonthlyList, self).__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=values.unset, start_date=values.unset, - end_date=values.unset, limit=None, page_size=None): - """ - 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 category - :param date start_date: The start_date - :param date end_date: The end_date - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.usage.record.monthly.MonthlyInstance] - """ - limits = self._version.read_limits(limit, page_size) +class MonthlyInstance(InstanceResource): - page = self.page( - category=category, - start_date=start_date, - end_date=end_date, - page_size=limits['page_size'], + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, limit=None, page_size=None): - """ - 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 category - :param date start_date: The start_date - :param date end_date: The end_date - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.usage.record.monthly.MonthlyInstance] - """ - return list(self.stream( - category=category, - start_date=start_date, - end_date=end_date, - limit=limit, - page_size=page_size, - )) - - def page(self, category=values.unset, start_date=values.unset, - end_date=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of MonthlyInstance records from the API. - Request is executed immediately - - :param MonthlyInstance.Category category: The category - :param date start_date: The start_date - :param date end_date: The end_date - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of MonthlyInstance - :rtype: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyPage - """ - params = values.of({ - 'Category': category, - 'StartDate': serialize.iso8601_date(start_date), - 'EndDate': serialize.iso8601_date(end_date), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" ) - - return MonthlyPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of MonthlyInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of MonthlyInstance - :rtype: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" ) - - return MonthlyPage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class MonthlyPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the MonthlyPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyPage - :rtype: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyPage - """ - super(MonthlyPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of MonthlyInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyInstance - :rtype: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyInstance - """ - return MonthlyInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class MonthlyInstance(InstanceResource): - """ """ - - class Category(object): + 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" @@ -228,6 +128,40 @@ class Category(object): 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" @@ -242,55 +176,155 @@ class Category(object): 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_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - 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_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = "marketplace-infogroup-dataaxle-bizinfo" + 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_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = "marketplace-keen-io-contact-center-analytics" + 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_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_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_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_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_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + 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_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" + 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" @@ -301,26 +335,59 @@ class Category(object): 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" - PCHAT_MESSAGES = "pchat-messages" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = "peer-to-peer-rooms-participant-minutes" + 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" @@ -331,28 +398,51 @@ class Category(object): 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" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" 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_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + 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" @@ -371,31 +461,157 @@ class Category(object): 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_AUDIO_TRACE = "voice-insights-audio-trace" - VOICE_INSIGHTS_CARRIER_CALLS = "voice-insights-carrier-calls" + 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_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" @@ -404,16 +620,30 @@ class Category(object): 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_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_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" @@ -424,157 +654,558 @@ class Category(object): 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_VOICE = "wireless-usage-voice" 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" - def __init__(self, version, payload, account_sid): - """ - Initialize the MonthlyInstance + """ + :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. + """ - :returns: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyInstance - :rtype: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyInstance - """ - super(MonthlyInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'api_version': payload['api_version'], - 'category': payload['category'], - 'count': payload['count'], - 'count_unit': payload['count_unit'], - 'description': payload['description'], - 'end_date': deserialize.iso8601_date(payload['end_date']), - 'price': deserialize.decimal(payload['price']), - 'price_unit': payload['price_unit'], - 'start_date': deserialize.iso8601_date(payload['start_date']), - 'subresource_uris': payload['subresource_uris'], - 'uri': payload['uri'], - 'usage': payload['usage'], - 'usage_unit': payload['usage_unit'], - } + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + 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") - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + self._solution = { + "account_sid": account_sid, + } - @property - def api_version(self): - """ - :returns: The api_version - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['api_version'] + Provide a friendly representation - @property - def category(self): - """ - :returns: The category - :rtype: MonthlyInstance.Category + :returns: Machine friendly representation """ - return self._properties['category'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - @property - def count(self): +class MonthlyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MonthlyInstance: """ - :returns: The count - :rtype: unicode + Build an instance of MonthlyInstance + + :param payload: Payload response from the API """ - return self._properties['count'] + return MonthlyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def count_unit(self): + def __repr__(self) -> str: """ - :returns: The count_unit - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['count_unit'] + return "" - @property - def description(self): + +class MonthlyList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - :returns: The description - :rtype: unicode + 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. + """ - return self._properties['description'] + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records/Monthly.json".format( + **self._solution + ) - @property - def end_date(self): + 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]: """ - :returns: The end_date - :rtype: date + 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 """ - return self._properties['end_date'] + 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"], + ) - @property - def price(self): + 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]: """ - :returns: The price - :rtype: unicode + 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 """ - return self._properties['price'] + 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"]) - @property - def price_unit(self): + 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]: """ - :returns: The price_unit - :rtype: unicode + 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 self._properties['price_unit'] + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) - @property - def start_date(self): + 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]: """ - :returns: The start_date - :rtype: date + 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 self._properties['start_date'] + 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, + ) + ] - @property - def subresource_uris(self): + 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: """ - :returns: The subresource_uris - :rtype: unicode + 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 """ - return self._properties['subresource_uris'] + 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, + } + ) - @property - def uri(self): + headers = values.of({"Content-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: """ - :returns: The uri - :rtype: unicode + 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 """ - return self._properties['uri'] + 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"}) - @property - def usage(self): + 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: """ - :returns: The usage - :rtype: unicode + 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 """ - return self._properties['usage'] + response = self._version.domain.twilio.request("GET", target_url) + return MonthlyPage(self._version, response, self._solution) - @property - def usage_unit(self): + async def get_page_async(self, target_url: str) -> MonthlyPage: """ - :returns: The usage_unit - :rtype: unicode + 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 """ - return self._properties['usage_unit'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return MonthlyPage(self._version, response, self._solution) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/api/v2010/account/usage/record/this_month.py b/twilio/rest/api/v2010/account/usage/record/this_month.py index d48ff3ea47..ab65a177d3 100644 --- a/twilio/rest/api/v2010/account/usage/record/this_month.py +++ b/twilio/rest/api/v2010/account/usage/record/this_month.py @@ -1,225 +1,125 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 ThisMonthList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the ThisMonthList - - :param Version version: Version that contains the resource - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthList - :rtype: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthList - """ - super(ThisMonthList, self).__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=values.unset, start_date=values.unset, - end_date=values.unset, limit=None, page_size=None): - """ - 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 category - :param date start_date: The start_date - :param date end_date: The end_date - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthInstance] - """ - limits = self._version.read_limits(limit, page_size) +class ThisMonthInstance(InstanceResource): - page = self.page( - category=category, - start_date=start_date, - end_date=end_date, - page_size=limits['page_size'], + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, limit=None, page_size=None): - """ - 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 category - :param date start_date: The start_date - :param date end_date: The end_date - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthInstance] - """ - return list(self.stream( - category=category, - start_date=start_date, - end_date=end_date, - limit=limit, - page_size=page_size, - )) - - def page(self, category=values.unset, start_date=values.unset, - end_date=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of ThisMonthInstance records from the API. - Request is executed immediately - - :param ThisMonthInstance.Category category: The category - :param date start_date: The start_date - :param date end_date: The end_date - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of ThisMonthInstance - :rtype: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthPage - """ - params = values.of({ - 'Category': category, - 'StartDate': serialize.iso8601_date(start_date), - 'EndDate': serialize.iso8601_date(end_date), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" ) - - return ThisMonthPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of ThisMonthInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of ThisMonthInstance - :rtype: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" ) - - return ThisMonthPage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ThisMonthPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the ThisMonthPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthPage - :rtype: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthPage - """ - super(ThisMonthPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of ThisMonthInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthInstance - :rtype: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthInstance - """ - return ThisMonthInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ThisMonthInstance(InstanceResource): - """ """ - - class Category(object): + 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" @@ -228,6 +128,40 @@ class Category(object): 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" @@ -242,55 +176,155 @@ class Category(object): 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_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - 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_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = "marketplace-infogroup-dataaxle-bizinfo" + 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_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = "marketplace-keen-io-contact-center-analytics" + 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_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_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_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_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_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + 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_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" + 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" @@ -301,26 +335,59 @@ class Category(object): 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" - PCHAT_MESSAGES = "pchat-messages" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = "peer-to-peer-rooms-participant-minutes" + 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" @@ -331,28 +398,51 @@ class Category(object): 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" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" 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_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + 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" @@ -371,31 +461,157 @@ class Category(object): 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_AUDIO_TRACE = "voice-insights-audio-trace" - VOICE_INSIGHTS_CARRIER_CALLS = "voice-insights-carrier-calls" + 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_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" @@ -404,16 +620,30 @@ class Category(object): 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_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_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" @@ -424,157 +654,558 @@ class Category(object): 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_VOICE = "wireless-usage-voice" 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" - def __init__(self, version, payload, account_sid): - """ - Initialize the ThisMonthInstance + """ + :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. + """ - :returns: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthInstance - :rtype: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthInstance - """ - super(ThisMonthInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'api_version': payload['api_version'], - 'category': payload['category'], - 'count': payload['count'], - 'count_unit': payload['count_unit'], - 'description': payload['description'], - 'end_date': deserialize.iso8601_date(payload['end_date']), - 'price': deserialize.decimal(payload['price']), - 'price_unit': payload['price_unit'], - 'start_date': deserialize.iso8601_date(payload['start_date']), - 'subresource_uris': payload['subresource_uris'], - 'uri': payload['uri'], - 'usage': payload['usage'], - 'usage_unit': payload['usage_unit'], - } + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + 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") - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + self._solution = { + "account_sid": account_sid, + } - @property - def api_version(self): - """ - :returns: The api_version - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['api_version'] + Provide a friendly representation - @property - def category(self): - """ - :returns: The category - :rtype: ThisMonthInstance.Category + :returns: Machine friendly representation """ - return self._properties['category'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - @property - def count(self): +class ThisMonthPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ThisMonthInstance: """ - :returns: The count - :rtype: unicode + Build an instance of ThisMonthInstance + + :param payload: Payload response from the API """ - return self._properties['count'] + return ThisMonthInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def count_unit(self): + def __repr__(self) -> str: """ - :returns: The count_unit - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['count_unit'] + return "" - @property - def description(self): + +class ThisMonthList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - :returns: The description - :rtype: unicode + 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. + """ - return self._properties['description'] + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records/ThisMonth.json".format( + **self._solution + ) - @property - def end_date(self): + 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]: """ - :returns: The end_date - :rtype: date + 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 """ - return self._properties['end_date'] + 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"], + ) - @property - def price(self): + 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]: """ - :returns: The price - :rtype: unicode + 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 """ - return self._properties['price'] + 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"]) - @property - def price_unit(self): + 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]: """ - :returns: The price_unit - :rtype: unicode + 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 self._properties['price_unit'] + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) - @property - def start_date(self): + 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]: """ - :returns: The start_date - :rtype: date + 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 self._properties['start_date'] + 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, + ) + ] - @property - def subresource_uris(self): + 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: """ - :returns: The subresource_uris - :rtype: unicode + 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 """ - return self._properties['subresource_uris'] + 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, + } + ) - @property - def uri(self): + headers = values.of({"Content-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: """ - :returns: The uri - :rtype: unicode + 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 """ - return self._properties['uri'] + 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"}) - @property - def usage(self): + 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: """ - :returns: The usage - :rtype: unicode + 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 """ - return self._properties['usage'] + response = self._version.domain.twilio.request("GET", target_url) + return ThisMonthPage(self._version, response, self._solution) - @property - def usage_unit(self): + async def get_page_async(self, target_url: str) -> ThisMonthPage: """ - :returns: The usage_unit - :rtype: unicode + 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 """ - return self._properties['usage_unit'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return ThisMonthPage(self._version, response, self._solution) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/api/v2010/account/usage/record/today.py b/twilio/rest/api/v2010/account/usage/record/today.py index d60c3bfaa9..393238e76f 100644 --- a/twilio/rest/api/v2010/account/usage/record/today.py +++ b/twilio/rest/api/v2010/account/usage/record/today.py @@ -1,225 +1,125 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 TodayList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the TodayList - - :param Version version: Version that contains the resource - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.usage.record.today.TodayList - :rtype: twilio.rest.api.v2010.account.usage.record.today.TodayList - """ - super(TodayList, self).__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=values.unset, start_date=values.unset, - end_date=values.unset, limit=None, page_size=None): - """ - 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 category - :param date start_date: The start_date - :param date end_date: The end_date - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.usage.record.today.TodayInstance] - """ - limits = self._version.read_limits(limit, page_size) +class TodayInstance(InstanceResource): - page = self.page( - category=category, - start_date=start_date, - end_date=end_date, - page_size=limits['page_size'], + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, limit=None, page_size=None): - """ - 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 category - :param date start_date: The start_date - :param date end_date: The end_date - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.usage.record.today.TodayInstance] - """ - return list(self.stream( - category=category, - start_date=start_date, - end_date=end_date, - limit=limit, - page_size=page_size, - )) - - def page(self, category=values.unset, start_date=values.unset, - end_date=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of TodayInstance records from the API. - Request is executed immediately - - :param TodayInstance.Category category: The category - :param date start_date: The start_date - :param date end_date: The end_date - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of TodayInstance - :rtype: twilio.rest.api.v2010.account.usage.record.today.TodayPage - """ - params = values.of({ - 'Category': category, - 'StartDate': serialize.iso8601_date(start_date), - 'EndDate': serialize.iso8601_date(end_date), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" ) - - return TodayPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of TodayInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of TodayInstance - :rtype: twilio.rest.api.v2010.account.usage.record.today.TodayPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" ) - - return TodayPage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class TodayPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the TodayPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.usage.record.today.TodayPage - :rtype: twilio.rest.api.v2010.account.usage.record.today.TodayPage - """ - super(TodayPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of TodayInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.usage.record.today.TodayInstance - :rtype: twilio.rest.api.v2010.account.usage.record.today.TodayInstance - """ - return TodayInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class TodayInstance(InstanceResource): - """ """ - - class Category(object): + 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" @@ -228,6 +128,40 @@ class Category(object): 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" @@ -242,55 +176,155 @@ class Category(object): 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_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - 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_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = "marketplace-infogroup-dataaxle-bizinfo" + 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_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = "marketplace-keen-io-contact-center-analytics" + 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_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_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_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_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_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + 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_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" + 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" @@ -301,26 +335,59 @@ class Category(object): 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" - PCHAT_MESSAGES = "pchat-messages" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = "peer-to-peer-rooms-participant-minutes" + 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" @@ -331,28 +398,51 @@ class Category(object): 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" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" 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_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + 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" @@ -371,31 +461,157 @@ class Category(object): 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_AUDIO_TRACE = "voice-insights-audio-trace" - VOICE_INSIGHTS_CARRIER_CALLS = "voice-insights-carrier-calls" + 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_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" @@ -404,16 +620,30 @@ class Category(object): 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_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_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" @@ -424,157 +654,558 @@ class Category(object): 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_VOICE = "wireless-usage-voice" 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" - def __init__(self, version, payload, account_sid): - """ - Initialize the TodayInstance + """ + :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. + """ - :returns: twilio.rest.api.v2010.account.usage.record.today.TodayInstance - :rtype: twilio.rest.api.v2010.account.usage.record.today.TodayInstance - """ - super(TodayInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'api_version': payload['api_version'], - 'category': payload['category'], - 'count': payload['count'], - 'count_unit': payload['count_unit'], - 'description': payload['description'], - 'end_date': deserialize.iso8601_date(payload['end_date']), - 'price': deserialize.decimal(payload['price']), - 'price_unit': payload['price_unit'], - 'start_date': deserialize.iso8601_date(payload['start_date']), - 'subresource_uris': payload['subresource_uris'], - 'uri': payload['uri'], - 'usage': payload['usage'], - 'usage_unit': payload['usage_unit'], - } + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + 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") - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + self._solution = { + "account_sid": account_sid, + } - @property - def api_version(self): - """ - :returns: The api_version - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['api_version'] + Provide a friendly representation - @property - def category(self): - """ - :returns: The category - :rtype: TodayInstance.Category + :returns: Machine friendly representation """ - return self._properties['category'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - @property - def count(self): +class TodayPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TodayInstance: """ - :returns: The count - :rtype: unicode + Build an instance of TodayInstance + + :param payload: Payload response from the API """ - return self._properties['count'] + return TodayInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def count_unit(self): + def __repr__(self) -> str: """ - :returns: The count_unit - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['count_unit'] + return "" - @property - def description(self): + +class TodayList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - :returns: The description - :rtype: unicode + 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. + """ - return self._properties['description'] + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records/Today.json".format( + **self._solution + ) - @property - def end_date(self): + 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]: """ - :returns: The end_date - :rtype: date + 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 """ - return self._properties['end_date'] + 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"], + ) - @property - def price(self): + 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]: """ - :returns: The price - :rtype: unicode + 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 """ - return self._properties['price'] + 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"]) - @property - def price_unit(self): + 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]: """ - :returns: The price_unit - :rtype: unicode + 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 self._properties['price_unit'] + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) - @property - def start_date(self): + 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]: """ - :returns: The start_date - :rtype: date + 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 self._properties['start_date'] + 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, + ) + ] - @property - def subresource_uris(self): + 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: """ - :returns: The subresource_uris - :rtype: unicode + 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 """ - return self._properties['subresource_uris'] + 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, + } + ) - @property - def uri(self): + headers = values.of({"Content-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: """ - :returns: The uri - :rtype: unicode + 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 """ - return self._properties['uri'] + 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"}) - @property - def usage(self): + 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: """ - :returns: The usage - :rtype: unicode + 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 """ - return self._properties['usage'] + response = self._version.domain.twilio.request("GET", target_url) + return TodayPage(self._version, response, self._solution) - @property - def usage_unit(self): + async def get_page_async(self, target_url: str) -> TodayPage: """ - :returns: The usage_unit - :rtype: unicode + 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 """ - return self._properties['usage_unit'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return TodayPage(self._version, response, self._solution) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/api/v2010/account/usage/record/yearly.py b/twilio/rest/api/v2010/account/usage/record/yearly.py index a19fff3c34..ad9e5a36d8 100644 --- a/twilio/rest/api/v2010/account/usage/record/yearly.py +++ b/twilio/rest/api/v2010/account/usage/record/yearly.py @@ -1,225 +1,125 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 YearlyList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the YearlyList - - :param Version version: Version that contains the resource - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.usage.record.yearly.YearlyList - :rtype: twilio.rest.api.v2010.account.usage.record.yearly.YearlyList - """ - super(YearlyList, self).__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=values.unset, start_date=values.unset, - end_date=values.unset, limit=None, page_size=None): - """ - 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 category - :param date start_date: The start_date - :param date end_date: The end_date - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.usage.record.yearly.YearlyInstance] - """ - limits = self._version.read_limits(limit, page_size) +class YearlyInstance(InstanceResource): - page = self.page( - category=category, - start_date=start_date, - end_date=end_date, - page_size=limits['page_size'], + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, limit=None, page_size=None): - """ - 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 category - :param date start_date: The start_date - :param date end_date: The end_date - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.usage.record.yearly.YearlyInstance] - """ - return list(self.stream( - category=category, - start_date=start_date, - end_date=end_date, - limit=limit, - page_size=page_size, - )) - - def page(self, category=values.unset, start_date=values.unset, - end_date=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of YearlyInstance records from the API. - Request is executed immediately - - :param YearlyInstance.Category category: The category - :param date start_date: The start_date - :param date end_date: The end_date - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of YearlyInstance - :rtype: twilio.rest.api.v2010.account.usage.record.yearly.YearlyPage - """ - params = values.of({ - 'Category': category, - 'StartDate': serialize.iso8601_date(start_date), - 'EndDate': serialize.iso8601_date(end_date), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" ) - - return YearlyPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of YearlyInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of YearlyInstance - :rtype: twilio.rest.api.v2010.account.usage.record.yearly.YearlyPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" ) - - return YearlyPage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class YearlyPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the YearlyPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.usage.record.yearly.YearlyPage - :rtype: twilio.rest.api.v2010.account.usage.record.yearly.YearlyPage - """ - super(YearlyPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of YearlyInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.usage.record.yearly.YearlyInstance - :rtype: twilio.rest.api.v2010.account.usage.record.yearly.YearlyInstance - """ - return YearlyInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class YearlyInstance(InstanceResource): - """ """ - - class Category(object): + 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" @@ -228,6 +128,40 @@ class Category(object): 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" @@ -242,55 +176,155 @@ class Category(object): 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_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - 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_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = "marketplace-infogroup-dataaxle-bizinfo" + 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_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = "marketplace-keen-io-contact-center-analytics" + 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_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_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_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_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_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + 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_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" + 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" @@ -301,26 +335,59 @@ class Category(object): 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" - PCHAT_MESSAGES = "pchat-messages" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = "peer-to-peer-rooms-participant-minutes" + 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" @@ -331,28 +398,51 @@ class Category(object): 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" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" 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_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + 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" @@ -371,31 +461,157 @@ class Category(object): 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_AUDIO_TRACE = "voice-insights-audio-trace" - VOICE_INSIGHTS_CARRIER_CALLS = "voice-insights-carrier-calls" + 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_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" @@ -404,16 +620,30 @@ class Category(object): 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_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_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" @@ -424,157 +654,558 @@ class Category(object): 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_VOICE = "wireless-usage-voice" 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" - def __init__(self, version, payload, account_sid): - """ - Initialize the YearlyInstance + """ + :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. + """ - :returns: twilio.rest.api.v2010.account.usage.record.yearly.YearlyInstance - :rtype: twilio.rest.api.v2010.account.usage.record.yearly.YearlyInstance - """ - super(YearlyInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'api_version': payload['api_version'], - 'category': payload['category'], - 'count': payload['count'], - 'count_unit': payload['count_unit'], - 'description': payload['description'], - 'end_date': deserialize.iso8601_date(payload['end_date']), - 'price': deserialize.decimal(payload['price']), - 'price_unit': payload['price_unit'], - 'start_date': deserialize.iso8601_date(payload['start_date']), - 'subresource_uris': payload['subresource_uris'], - 'uri': payload['uri'], - 'usage': payload['usage'], - 'usage_unit': payload['usage_unit'], - } + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + 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") - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + self._solution = { + "account_sid": account_sid, + } - @property - def api_version(self): - """ - :returns: The api_version - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['api_version'] + Provide a friendly representation - @property - def category(self): - """ - :returns: The category - :rtype: YearlyInstance.Category + :returns: Machine friendly representation """ - return self._properties['category'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - @property - def count(self): +class YearlyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> YearlyInstance: """ - :returns: The count - :rtype: unicode + Build an instance of YearlyInstance + + :param payload: Payload response from the API """ - return self._properties['count'] + return YearlyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def count_unit(self): + def __repr__(self) -> str: """ - :returns: The count_unit - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['count_unit'] + return "" - @property - def description(self): + +class YearlyList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - :returns: The description - :rtype: unicode + 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. + """ - return self._properties['description'] + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records/Yearly.json".format( + **self._solution + ) - @property - def end_date(self): + 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]: """ - :returns: The end_date - :rtype: date + 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 """ - return self._properties['end_date'] + 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"], + ) - @property - def price(self): + 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]: """ - :returns: The price - :rtype: unicode + 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 """ - return self._properties['price'] + 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"]) - @property - def price_unit(self): + 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]: """ - :returns: The price_unit - :rtype: unicode + 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 self._properties['price_unit'] + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) - @property - def start_date(self): + 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]: """ - :returns: The start_date - :rtype: date + 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 self._properties['start_date'] + 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, + ) + ] - @property - def subresource_uris(self): + 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: """ - :returns: The subresource_uris - :rtype: unicode + 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 """ - return self._properties['subresource_uris'] + 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, + } + ) - @property - def uri(self): + headers = values.of({"Content-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: """ - :returns: The uri - :rtype: unicode + 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 """ - return self._properties['uri'] + 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"}) - @property - def usage(self): + 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: """ - :returns: The usage - :rtype: unicode + 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 """ - return self._properties['usage'] + response = self._version.domain.twilio.request("GET", target_url) + return YearlyPage(self._version, response, self._solution) - @property - def usage_unit(self): + async def get_page_async(self, target_url: str) -> YearlyPage: """ - :returns: The usage_unit - :rtype: unicode + 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 """ - return self._properties['usage_unit'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return YearlyPage(self._version, response, self._solution) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/api/v2010/account/usage/record/yesterday.py b/twilio/rest/api/v2010/account/usage/record/yesterday.py index 045faeda7f..f3aacda8b9 100644 --- a/twilio/rest/api/v2010/account/usage/record/yesterday.py +++ b/twilio/rest/api/v2010/account/usage/record/yesterday.py @@ -1,225 +1,125 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 YesterdayList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the YesterdayList - - :param Version version: Version that contains the resource - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayList - :rtype: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayList - """ - super(YesterdayList, self).__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=values.unset, start_date=values.unset, - end_date=values.unset, limit=None, page_size=None): - """ - 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 category - :param date start_date: The start_date - :param date end_date: The end_date - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayInstance] - """ - limits = self._version.read_limits(limit, page_size) +class YesterdayInstance(InstanceResource): - page = self.page( - category=category, - start_date=start_date, - end_date=end_date, - page_size=limits['page_size'], + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, limit=None, page_size=None): - """ - 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 category - :param date start_date: The start_date - :param date end_date: The end_date - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayInstance] - """ - return list(self.stream( - category=category, - start_date=start_date, - end_date=end_date, - limit=limit, - page_size=page_size, - )) - - def page(self, category=values.unset, start_date=values.unset, - end_date=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of YesterdayInstance records from the API. - Request is executed immediately - - :param YesterdayInstance.Category category: The category - :param date start_date: The start_date - :param date end_date: The end_date - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of YesterdayInstance - :rtype: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayPage - """ - params = values.of({ - 'Category': category, - 'StartDate': serialize.iso8601_date(start_date), - 'EndDate': serialize.iso8601_date(end_date), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" ) - - return YesterdayPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of YesterdayInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of YesterdayInstance - :rtype: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" ) - - return YesterdayPage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class YesterdayPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the YesterdayPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayPage - :rtype: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayPage - """ - super(YesterdayPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of YesterdayInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayInstance - :rtype: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayInstance - """ - return YesterdayInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class YesterdayInstance(InstanceResource): - """ """ - - class Category(object): + 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" @@ -228,6 +128,40 @@ class Category(object): 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" @@ -242,55 +176,155 @@ class Category(object): 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_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - 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_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = "marketplace-infogroup-dataaxle-bizinfo" + 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_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = "marketplace-keen-io-contact-center-analytics" + 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_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_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_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_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_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + 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_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" + 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" @@ -301,26 +335,59 @@ class Category(object): 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" - PCHAT_MESSAGES = "pchat-messages" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = "peer-to-peer-rooms-participant-minutes" + 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" @@ -331,28 +398,51 @@ class Category(object): 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" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" 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_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + 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" @@ -371,31 +461,157 @@ class Category(object): 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_AUDIO_TRACE = "voice-insights-audio-trace" - VOICE_INSIGHTS_CARRIER_CALLS = "voice-insights-carrier-calls" + 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_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" @@ -404,16 +620,30 @@ class Category(object): 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_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_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" @@ -424,157 +654,558 @@ class Category(object): 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_VOICE = "wireless-usage-voice" 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" - def __init__(self, version, payload, account_sid): - """ - Initialize the YesterdayInstance + """ + :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. + """ - :returns: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayInstance - :rtype: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayInstance - """ - super(YesterdayInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'api_version': payload['api_version'], - 'category': payload['category'], - 'count': payload['count'], - 'count_unit': payload['count_unit'], - 'description': payload['description'], - 'end_date': deserialize.iso8601_date(payload['end_date']), - 'price': deserialize.decimal(payload['price']), - 'price_unit': payload['price_unit'], - 'start_date': deserialize.iso8601_date(payload['start_date']), - 'subresource_uris': payload['subresource_uris'], - 'uri': payload['uri'], - 'usage': payload['usage'], - 'usage_unit': payload['usage_unit'], - } + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + 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") - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + self._solution = { + "account_sid": account_sid, + } - @property - def api_version(self): - """ - :returns: The api_version - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['api_version'] + Provide a friendly representation - @property - def category(self): - """ - :returns: The category - :rtype: YesterdayInstance.Category + :returns: Machine friendly representation """ - return self._properties['category'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - @property - def count(self): +class YesterdayPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> YesterdayInstance: """ - :returns: The count - :rtype: unicode + Build an instance of YesterdayInstance + + :param payload: Payload response from the API """ - return self._properties['count'] + return YesterdayInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def count_unit(self): + def __repr__(self) -> str: """ - :returns: The count_unit - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['count_unit'] + return "" - @property - def description(self): + +class YesterdayList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - :returns: The description - :rtype: unicode + 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. + """ - return self._properties['description'] + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records/Yesterday.json".format( + **self._solution + ) - @property - def end_date(self): + 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]: """ - :returns: The end_date - :rtype: date + 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 """ - return self._properties['end_date'] + 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"], + ) - @property - def price(self): + 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]: """ - :returns: The price - :rtype: unicode + 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 """ - return self._properties['price'] + 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"]) - @property - def price_unit(self): + 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]: """ - :returns: The price_unit - :rtype: unicode + 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 self._properties['price_unit'] + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) - @property - def start_date(self): + 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]: """ - :returns: The start_date - :rtype: date + 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 self._properties['start_date'] + 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, + ) + ] - @property - def subresource_uris(self): + 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: """ - :returns: The subresource_uris - :rtype: unicode + 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 """ - return self._properties['subresource_uris'] + 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, + } + ) - @property - def uri(self): + headers = values.of({"Content-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: """ - :returns: The uri - :rtype: unicode + 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 """ - return self._properties['uri'] + 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"}) - @property - def usage(self): + 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: """ - :returns: The usage - :rtype: unicode + 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 """ - return self._properties['usage'] + response = self._version.domain.twilio.request("GET", target_url) + return YesterdayPage(self._version, response, self._solution) - @property - def usage_unit(self): + async def get_page_async(self, target_url: str) -> YesterdayPage: """ - :returns: The usage_unit - :rtype: unicode + 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 """ - return self._properties['usage_unit'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return YesterdayPage(self._version, response, self._solution) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/api/v2010/account/usage/trigger.py b/twilio/rest/api/v2010/account/usage/trigger.py index e5c62f9582..7f182a01b3 100644 --- a/twilio/rest/api/v2010/account/usage/trigger.py +++ b/twilio/rest/api/v2010/account/usage/trigger.py @@ -1,375 +1,136 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 TriggerList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the TriggerList - - :param Version version: Version that contains the resource - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.usage.trigger.TriggerList - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerList - """ - super(TriggerList, self).__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, trigger_value, usage_category, - callback_method=values.unset, friendly_name=values.unset, - recurring=values.unset, trigger_by=values.unset): - """ - Create a new TriggerInstance - - :param unicode callback_url: URL Twilio will request when the trigger fires - :param unicode trigger_value: the value at which the trigger will fire - :param TriggerInstance.UsageCategory usage_category: The usage category the trigger watches - :param unicode callback_method: HTTP method to use with callback_url - :param unicode friendly_name: A user-specified, human-readable name for the trigger. - :param TriggerInstance.Recurring recurring: How this trigger recurs - :param TriggerInstance.TriggerField trigger_by: The field in the UsageRecord that fires the trigger - - :returns: Newly created TriggerInstance - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerInstance - """ - data = values.of({ - 'CallbackUrl': callback_url, - 'TriggerValue': trigger_value, - 'UsageCategory': usage_category, - 'CallbackMethod': callback_method, - 'FriendlyName': friendly_name, - 'Recurring': recurring, - 'TriggerBy': trigger_by, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return TriggerInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - def stream(self, recurring=values.unset, trigger_by=values.unset, - usage_category=values.unset, limit=None, page_size=None): - """ - 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: Filter by recurring - :param TriggerInstance.TriggerField trigger_by: Filter by trigger by - :param TriggerInstance.UsageCategory usage_category: Filter by Usage Category - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.usage.trigger.TriggerInstance] - """ - 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'], limits['page_limit']) - - def list(self, recurring=values.unset, trigger_by=values.unset, - usage_category=values.unset, limit=None, page_size=None): - """ - 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: Filter by recurring - :param TriggerInstance.TriggerField trigger_by: Filter by trigger by - :param TriggerInstance.UsageCategory usage_category: Filter by Usage Category - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.usage.trigger.TriggerInstance] - """ - return list(self.stream( - recurring=recurring, - trigger_by=trigger_by, - usage_category=usage_category, - limit=limit, - page_size=page_size, - )) - - def page(self, recurring=values.unset, trigger_by=values.unset, - usage_category=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of TriggerInstance records from the API. - Request is executed immediately - - :param TriggerInstance.Recurring recurring: Filter by recurring - :param TriggerInstance.TriggerField trigger_by: Filter by trigger by - :param TriggerInstance.UsageCategory usage_category: Filter by Usage Category - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of TriggerInstance - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerPage - """ - params = values.of({ - 'Recurring': recurring, - 'TriggerBy': trigger_by, - 'UsageCategory': usage_category, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return TriggerPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of TriggerInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of TriggerInstance - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return TriggerPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a TriggerContext - - :param sid: Fetch by unique usage-trigger Sid - - :returns: twilio.rest.api.v2010.account.usage.trigger.TriggerContext - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerContext - """ - return TriggerContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a TriggerContext - - :param sid: Fetch by unique usage-trigger Sid - - :returns: twilio.rest.api.v2010.account.usage.trigger.TriggerContext - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerContext - """ - return TriggerContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class TriggerPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the TriggerPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.api.v2010.account.usage.trigger.TriggerPage - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerPage - """ - super(TriggerPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of TriggerInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.usage.trigger.TriggerInstance - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerInstance - """ - return TriggerInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class TriggerContext(InstanceContext): - """ """ - - def __init__(self, version, account_sid, sid): - """ - Initialize the TriggerContext - - :param Version version: Version that contains the resource - :param account_sid: The account_sid - :param sid: Fetch by unique usage-trigger Sid - - :returns: twilio.rest.api.v2010.account.usage.trigger.TriggerContext - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerContext - """ - super(TriggerContext, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/Usage/Triggers/{sid}.json'.format(**self._solution) +class TriggerInstance(InstanceResource): - def fetch(self): - """ - Fetch a TriggerInstance + class Recurring(object): + DAILY = "daily" + MONTHLY = "monthly" + YEARLY = "yearly" + ALLTIME = "alltime" - :returns: Fetched TriggerInstance - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerInstance - """ - params = values.of({}) + class TriggerField(object): + COUNT = "count" + USAGE = "usage" + PRICE = "price" - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + class UsageCategory(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" ) - - return TriggerInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" ) - - def update(self, callback_method=values.unset, callback_url=values.unset, - friendly_name=values.unset): - """ - Update the TriggerInstance - - :param unicode callback_method: HTTP method to use with callback_url - :param unicode callback_url: URL Twilio will request when the trigger fires - :param unicode friendly_name: A user-specified, human-readable name for the trigger. - - :returns: Updated TriggerInstance - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerInstance - """ - data = values.of({ - 'CallbackMethod': callback_method, - 'CallbackUrl': callback_url, - 'FriendlyName': friendly_name, - }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" ) - - return TriggerInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" ) - - def delete(self): - """ - Deletes the TriggerInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class TriggerInstance(InstanceResource): - """ """ - - class UsageCategory(object): + 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" @@ -378,6 +139,40 @@ class UsageCategory(object): 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" @@ -392,55 +187,155 @@ class UsageCategory(object): 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_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - 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_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = "marketplace-infogroup-dataaxle-bizinfo" + 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_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = "marketplace-keen-io-contact-center-analytics" + 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_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_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_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_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_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + 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_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" + 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" @@ -451,26 +346,59 @@ class UsageCategory(object): 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" - PCHAT_MESSAGES = "pchat-messages" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = "peer-to-peer-rooms-participant-minutes" + 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" @@ -481,28 +409,51 @@ class UsageCategory(object): 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" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" 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_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + 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" @@ -521,31 +472,157 @@ class UsageCategory(object): 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_AUDIO_TRACE = "voice-insights-audio-trace" - VOICE_INSIGHTS_CARRIER_CALLS = "voice-insights-carrier-calls" + 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_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" @@ -554,16 +631,30 @@ class UsageCategory(object): 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_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_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" @@ -574,240 +665,947 @@ class UsageCategory(object): 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_VOICE = "wireless-usage-voice" 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") - class Recurring(object): - DAILY = "daily" - MONTHLY = "monthly" - YEARLY = "yearly" - ALLTIME = "alltime" - - class TriggerField(object): - COUNT = "count" - USAGE = "usage" - PRICE = "price" - - def __init__(self, version, payload, account_sid, sid=None): - """ - Initialize the TriggerInstance - - :returns: twilio.rest.api.v2010.account.usage.trigger.TriggerInstance - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerInstance - """ - super(TriggerInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'api_version': payload['api_version'], - 'callback_method': payload['callback_method'], - 'callback_url': payload['callback_url'], - 'current_value': payload['current_value'], - 'date_created': deserialize.rfc2822_datetime(payload['date_created']), - 'date_fired': deserialize.rfc2822_datetime(payload['date_fired']), - 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), - 'friendly_name': payload['friendly_name'], - 'recurring': payload['recurring'], - 'sid': payload['sid'], - 'trigger_by': payload['trigger_by'], - 'trigger_value': payload['trigger_value'], - 'uri': payload['uri'], - 'usage_category': payload['usage_category'], - 'usage_record_uri': payload['usage_record_uri'], + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, } - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } + self._context: Optional[TriggerContext] = None @property - def _proxy(self): + 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 + performing various actions. All instance actions are proxied to the context :returns: TriggerContext for this TriggerInstance - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerContext """ if self._context is None: self._context = TriggerContext( self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) return self._context - @property - def account_sid(self): + def delete(self) -> bool: """ - :returns: The account this trigger monitors. - :rtype: unicode + Deletes the TriggerInstance + + + :returns: True if delete succeeds, False otherwise """ - return self._properties['account_sid'] + return self._proxy.delete() - @property - def api_version(self): + async def delete_async(self) -> bool: """ - :returns: The api_version - :rtype: unicode + Asynchronous coroutine that deletes the TriggerInstance + + + :returns: True if delete succeeds, False otherwise """ - return self._properties['api_version'] + return await self._proxy.delete_async() - @property - def callback_method(self): + def fetch(self) -> "TriggerInstance": """ - :returns: HTTP method to use with callback_url - :rtype: unicode + Fetch the TriggerInstance + + + :returns: The fetched TriggerInstance """ - return self._properties['callback_method'] + return self._proxy.fetch() - @property - def callback_url(self): + async def fetch_async(self) -> "TriggerInstance": """ - :returns: URL Twilio will request when the trigger fires - :rtype: unicode + Asynchronous coroutine to fetch the TriggerInstance + + + :returns: The fetched TriggerInstance """ - return self._properties['callback_url'] + return await self._proxy.fetch_async() - @property - def current_value(self): + 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": """ - :returns: The current value of the field the trigger is watching. - :rtype: unicode + 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._properties['current_value'] + return self._proxy.update( + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + ) - @property - def date_created(self): + 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": """ - :returns: The date this resource was created - :rtype: datetime + 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 self._properties['date_created'] + return await self._proxy.update_async( + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + ) - @property - def date_fired(self): + def __repr__(self) -> str: """ - :returns: The date the trigger was last fired - :rtype: datetime + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['date_fired'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def date_updated(self): + +class TriggerContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): """ - :returns: The date this resource was last updated - :rtype: datetime + 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. """ - return self._properties['date_updated'] + super().__init__(version) - @property - def friendly_name(self): + # 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: """ - :returns: A user-specified, human-readable name for the trigger. - :rtype: unicode + Deletes the TriggerInstance + + + :returns: True if delete succeeds, False otherwise """ - return self._properties['friendly_name'] - @property - def recurring(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - :returns: How this trigger recurs - :rtype: TriggerInstance.Recurring + Asynchronous coroutine that deletes the TriggerInstance + + + :returns: True if delete succeeds, False otherwise """ - return self._properties['recurring'] - @property - def sid(self): + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TriggerInstance: """ - :returns: The trigger's unique Sid - :rtype: unicode + Fetch the TriggerInstance + + + :returns: The fetched TriggerInstance """ - return self._properties['sid'] - @property - def trigger_by(self): + 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: """ - :returns: The field in the UsageRecord that fires the trigger - :rtype: TriggerInstance.TriggerField + Asynchronous coroutine to fetch the TriggerInstance + + + :returns: The fetched TriggerInstance """ - return self._properties['trigger_by'] - @property - def trigger_value(self): + 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: """ - :returns: the value at which the trigger will fire - :rtype: unicode + 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._properties['trigger_value'] - @property - def uri(self): + 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: """ - :returns: The URI for this resource - :rtype: unicode + 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 self._properties['uri'] - @property - def usage_category(self): + 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 """ - :returns: The usage category the trigger watches - :rtype: TriggerInstance.UsageCategory + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TriggerPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TriggerInstance: """ - return self._properties['usage_category'] + Build an instance of TriggerInstance - @property - def usage_record_uri(self): + :param payload: Payload response from the API """ - :returns: The URI of the UsageRecord this trigger is watching - :rtype: unicode + return TriggerInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: """ - return self._properties['usage_record_uri'] + Provide a friendly representation - def fetch(self): + :returns: Machine friendly representation """ - Fetch a TriggerInstance + return "" - :returns: Fetched TriggerInstance - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerInstance + +class TriggerList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - return self._proxy.fetch() + 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. - def update(self, callback_method=values.unset, callback_url=values.unset, - friendly_name=values.unset): """ - Update the TriggerInstance + 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" - :param unicode callback_method: HTTP method to use with callback_url - :param unicode callback_url: URL Twilio will request when the trigger fires - :param unicode friendly_name: A user-specified, human-readable name for the trigger. + headers["Accept"] = "application/json" - :returns: Updated TriggerInstance - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerInstance + 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]: """ - return self._proxy.update( - callback_method=callback_method, - callback_url=callback_url, - friendly_name=friendly_name, + 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"], ) - def delete(self): + 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]: """ - Deletes the 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. - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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 """ - return self._proxy.delete() + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/api/v2010/account/validation_request.py b/twilio/rest/api/v2010/account/validation_request.py index cff599a3a0..d92f840e68 100644 --- a/twilio/rest/api/v2010/account/validation_request.py +++ b/twilio/rest/api/v2010/account/validation_request.py @@ -1,190 +1,173 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize +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.page import Page - - -class ValidationRequestList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the ValidationRequestList - - :param Version version: Version that contains the resource - :param account_sid: The account_sid - - :returns: twilio.rest.api.v2010.account.validation_request.ValidationRequestList - :rtype: twilio.rest.api.v2010.account.validation_request.ValidationRequestList - """ - super(ValidationRequestList, self).__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, friendly_name=values.unset, - call_delay=values.unset, extension=values.unset, - status_callback=values.unset, status_callback_method=values.unset): - """ - Create a new ValidationRequestInstance +from twilio.base.version import Version - :param unicode phone_number: The phone_number - :param unicode friendly_name: The friendly_name - :param unicode call_delay: The call_delay - :param unicode extension: The extension - :param unicode status_callback: The status_callback - :param unicode status_callback_method: The status_callback_method - :returns: Newly created ValidationRequestInstance - :rtype: twilio.rest.api.v2010.account.validation_request.ValidationRequestInstance - """ - data = values.of({ - 'PhoneNumber': phone_number, - 'FriendlyName': friendly_name, - 'CallDelay': call_delay, - 'Extension': extension, - 'StatusCallback': status_callback, - 'StatusCallbackMethod': status_callback_method, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return ValidationRequestInstance(self._version, payload, account_sid=self._solution['account_sid'], ) +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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ValidationRequestPage(Page): - """ """ +class ValidationRequestList(ListResource): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str): """ - Initialize the ValidationRequestPage + Initialize the ValidationRequestList - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The account_sid + :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. - :returns: twilio.rest.api.v2010.account.validation_request.ValidationRequestPage - :rtype: twilio.rest.api.v2010.account.validation_request.ValidationRequestPage """ - super(ValidationRequestPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of ValidationRequestInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.validation_request.ValidationRequestInstance - :rtype: twilio.rest.api.v2010.account.validation_request.ValidationRequestInstance - """ - return ValidationRequestInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' + 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"}) -class ValidationRequestInstance(InstanceResource): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, payload, account_sid): - """ - Initialize the ValidationRequestInstance + headers["Accept"] = "application/json" - :returns: twilio.rest.api.v2010.account.validation_request.ValidationRequestInstance - :rtype: twilio.rest.api.v2010.account.validation_request.ValidationRequestInstance - """ - super(ValidationRequestInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'phone_number': payload['phone_number'], - 'friendly_name': payload['friendly_name'], - 'validation_code': deserialize.integer(payload['validation_code']), - 'call_sid': payload['call_sid'], - } + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + return ValidationRequestInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['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"}) - @property - def phone_number(self): - """ - :returns: The phone_number - :rtype: unicode - """ - return self._properties['phone_number'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] + headers["Accept"] = "application/json" - @property - def validation_code(self): - """ - :returns: The validation_code - :rtype: unicode - """ - return self._properties['validation_code'] + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def call_sid(self): - """ - :returns: The call_sid - :rtype: unicode - """ - return self._properties['call_sid'] + return ValidationRequestInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" 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 "" 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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "" + + +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 "" 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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "" + + +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 "" 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 "".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 "".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 "" 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 "" + + +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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "" 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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "" + + +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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" 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 "" diff --git a/twilio/rest/chat/__init__.py b/twilio/rest/chat/__init__.py index e295113051..9608a0fd87 100644 --- a/twilio/rest/chat/__init__.py +++ b/twilio/rest/chat/__init__.py @@ -1,72 +1,35 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" +from warnings import warn -from twilio.base.domain import Domain -from twilio.rest.chat.v1 import V1 -from twilio.rest.chat.v2 import V2 +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(Domain): - - def __init__(self, twilio): - """ - Initialize the Chat Domain - - :returns: Domain for Chat - :rtype: twilio.rest.chat.Chat - """ - super(Chat, self).__init__(twilio) - - self.base_url = 'https://chat.twilio.com' - - # Versions - self._v1 = None - self._v2 = None - +class Chat(ChatBase): @property - def v1(self): - """ - :returns: Version v1 of chat - :rtype: twilio.rest.chat.v1.V1 - """ - if self._v1 is None: - self._v1 = V1(self) - return self._v1 - - @property - def v2(self): - """ - :returns: Version v2 of chat - :rtype: twilio.rest.chat.v2.V2 - """ - if self._v2 is None: - self._v2 = V2(self) - return self._v2 - - @property - def credentials(self): - """ - :rtype: twilio.rest.chat.v2.credential.CredentialList - """ + def credentials(self) -> CredentialList: + warn( + "credentials is deprecated. Use v2.credentials instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v2.credentials @property - def services(self): - """ - :rtype: twilio.rest.chat.v2.service.ServiceList - """ + def services(self) -> ServiceList: + warn( + "services is deprecated. Use v2.services instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v2.services - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' + @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 index 44d2dab499..d0ade9eed5 100644 --- a/twilio/rest/chat/v1/__init__.py +++ b/twilio/rest/chat/v1/__init__.py @@ -1,53 +1,51 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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): + def __init__(self, domain: Domain): """ Initialize the V1 version of Chat - :returns: V1 version of Chat - :rtype: twilio.rest.chat.v1.V1.V1 + :param domain: The Twilio.chat domain """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._credentials = None - self._services = None + super().__init__(domain, "v1") + self._credentials: Optional[CredentialList] = None + self._services: Optional[ServiceList] = None @property - def credentials(self): - """ - :rtype: twilio.rest.chat.v1.credential.CredentialList - """ + def credentials(self) -> CredentialList: if self._credentials is None: self._credentials = CredentialList(self) return self._credentials @property - def services(self): - """ - :rtype: twilio.rest.chat.v1.service.ServiceList - """ + def services(self) -> ServiceList: if self._services is None: self._services = ServiceList(self) return self._services - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/chat/v1/credential.py b/twilio/rest/chat/v1/credential.py index 74f6551970..3bd48b1144 100644 --- a/twilio/rest/chat/v1/credential.py +++ b/twilio/rest/chat/v1/credential.py @@ -1,472 +1,711 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 CredentialList(ListResource): - """ """ - - def __init__(self, version): - """ - Initialize the CredentialList +class CredentialInstance(InstanceResource): - :param Version version: Version that contains the resource + class PushService(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" - :returns: twilio.rest.chat.v1.credential.CredentialList - :rtype: twilio.rest.chat.v1.credential.CredentialList - """ - super(CredentialList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {} - self._uri = '/Credentials'.format(**self._solution) + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CredentialContext] = None - def stream(self, limit=None, page_size=None): + @property + def _proxy(self) -> "CredentialContext": """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.credential.CredentialInstance] + :returns: CredentialContext for this CredentialInstance """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def list(self, limit=None, page_size=None): + def delete(self) -> bool: """ - Lists CredentialInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the CredentialInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.credential.CredentialInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.delete() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def delete_async(self) -> bool: """ - Retrieve a single page of CredentialInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the CredentialInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialPage + :returns: True if delete succeeds, False otherwise """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + return await self._proxy.delete_async() - return CredentialPage(self._version, response, self._solution) - - def get_page(self, target_url): + def fetch(self) -> "CredentialInstance": """ - Retrieve a specific page of CredentialInstance records from the API. - Request is executed immediately + Fetch the CredentialInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialPage + :returns: The fetched CredentialInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return CredentialPage(self._version, response, self._solution) + return self._proxy.fetch() - def create(self, type, friendly_name=values.unset, certificate=values.unset, - private_key=values.unset, sandbox=values.unset, api_key=values.unset, - secret=values.unset): + async def fetch_async(self) -> "CredentialInstance": """ - Create a new CredentialInstance + Asynchronous coroutine to fetch the CredentialInstance - :param CredentialInstance.PushService type: The type - :param unicode friendly_name: The friendly_name - :param unicode certificate: The certificate - :param unicode private_key: The private_key - :param bool sandbox: The sandbox - :param unicode api_key: The api_key - :param unicode secret: The secret - :returns: Newly created CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance + :returns: The fetched CredentialInstance """ - data = values.of({ - 'Type': type, - 'FriendlyName': friendly_name, - 'Certificate': certificate, - 'PrivateKey': private_key, - 'Sandbox': sandbox, - 'ApiKey': api_key, - 'Secret': secret, - }) + return await self._proxy.fetch_async() - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return CredentialInstance(self._version, payload, ) - - def get(self, 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": """ - Constructs a CredentialContext + Update the CredentialInstance - :param sid: The sid + :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: twilio.rest.chat.v1.credential.CredentialContext - :rtype: twilio.rest.chat.v1.credential.CredentialContext + :returns: The updated CredentialInstance """ - return CredentialContext(self._version, sid=sid, ) + return self._proxy.update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - def __call__(self, 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": """ - Constructs a CredentialContext + Asynchronous coroutine to update the CredentialInstance - :param sid: The sid + :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: twilio.rest.chat.v1.credential.CredentialContext - :rtype: twilio.rest.chat.v1.credential.CredentialContext + :returns: The updated CredentialInstance """ - return CredentialContext(self._version, sid=sid, ) + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class CredentialPage(Page): - """ """ +class CredentialContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the CredentialPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the CredentialContext - :returns: twilio.rest.chat.v1.credential.CredentialPage - :rtype: twilio.rest.chat.v1.credential.CredentialPage + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. """ - super(CredentialPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) - def get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of CredentialInstance + Deletes the CredentialInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v1.credential.CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance + :returns: True if delete succeeds, False otherwise """ - return CredentialInstance(self._version, payload, ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the CredentialInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class CredentialContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, sid): + def fetch(self) -> CredentialInstance: """ - Initialize the CredentialContext + Fetch the CredentialInstance - :param Version version: Version that contains the resource - :param sid: The sid - :returns: twilio.rest.chat.v1.credential.CredentialContext - :rtype: twilio.rest.chat.v1.credential.CredentialContext + :returns: The fetched CredentialInstance """ - super(CredentialContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Credentials/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialInstance: """ - Fetch a CredentialInstance + Asynchronous coroutine to fetch the CredentialInstance - :returns: Fetched CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance + + :returns: The fetched CredentialInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], ) + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def update(self, friendly_name=values.unset, certificate=values.unset, - private_key=values.unset, sandbox=values.unset, api_key=values.unset, - secret=values.unset): + 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 unicode friendly_name: The friendly_name - :param unicode certificate: The certificate - :param unicode private_key: The private_key - :param bool sandbox: The sandbox - :param unicode api_key: The api_key - :param unicode secret: The secret - - :returns: Updated CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Certificate': certificate, - 'PrivateKey': private_key, - 'Sandbox': sandbox, - 'ApiKey': api_key, - 'Secret': secret, - }) + :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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) - return CredentialInstance(self._version, payload, sid=self._solution['sid'], ) + 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({}) - def delete(self): - """ - Deletes the CredentialInstance + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + headers["Accept"] = "application/json" - def __repr__(self): + 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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class CredentialInstance(InstanceResource): - """ """ +class CredentialPage(Page): - class PushService(object): - GCM = "gcm" - APN = "apn" - FCM = "fcm" + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: + """ + Build an instance of CredentialInstance - def __init__(self, version, payload, sid=None): + :param payload: Payload response from the API """ - Initialize the CredentialInstance + return CredentialInstance(self._version, payload) - :returns: twilio.rest.chat.v1.credential.CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance + def __repr__(self) -> str: """ - super(CredentialInstance, self).__init__(version) + Provide a friendly representation - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'friendly_name': payload['friendly_name'], - 'type': payload['type'], - 'sandbox': payload['sandbox'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - } + :returns: Machine friendly representation + """ + return "" - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context +class CredentialList(ListResource): - :returns: CredentialContext for this CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialContext + def __init__(self, version: Version): """ - if self._context is None: - self._context = CredentialContext(self._version, sid=self._solution['sid'], ) - return self._context + Initialize the CredentialList + + :param version: Version that contains the resource - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode """ - return self._properties['sid'] + super().__init__(version) - @property - def account_sid(self): + 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: """ - :returns: The account_sid - :rtype: unicode + 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 """ - return self._properties['account_sid'] - @property - def friendly_name(self): + 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]: """ - :returns: The friendly_name - :rtype: unicode + 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 """ - return self._properties['friendly_name'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def type(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialInstance]: """ - :returns: The type - :rtype: CredentialInstance.PushService + 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 """ - return self._properties['type'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def sandbox(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: """ - :returns: The sandbox - :rtype: unicode + 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 self._properties['sandbox'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def date_created(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: """ - :returns: The date_created - :rtype: datetime + 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: """ - return self._properties['date_created'] + Retrieve a single page of CredentialInstance records from the API. + Request is executed immediately - @property - def date_updated(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The date_updated - :rtype: datetime + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page of CredentialInstance records from the API. + Request is executed immediately - @property - def url(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The url - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['url'] + Retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance """ - Fetch a CredentialInstance + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) - :returns: Fetched CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance + async def get_page_async(self, target_url: str) -> CredentialPage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately - def update(self, friendly_name=values.unset, certificate=values.unset, - private_key=values.unset, sandbox=values.unset, api_key=values.unset, - secret=values.unset): + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance """ - Update the CredentialInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response) - :param unicode friendly_name: The friendly_name - :param unicode certificate: The certificate - :param unicode private_key: The private_key - :param bool sandbox: The sandbox - :param unicode api_key: The api_key - :param unicode secret: The secret + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext - :returns: Updated CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. """ - return self._proxy.update( - friendly_name=friendly_name, - certificate=certificate, - private_key=private_key, - sandbox=sandbox, - api_key=api_key, - secret=secret, - ) + return CredentialContext(self._version, sid=sid) - def delete(self): + def __call__(self, sid: str) -> CredentialContext: """ - Deletes the CredentialInstance + Constructs a CredentialContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. """ - return self._proxy.delete() + return CredentialContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/chat/v1/service/__init__.py b/twilio/rest/chat/v1/service/__init__.py index f0110975e0..26fde4025b 100644 --- a/twilio/rest/chat/v1/service/__init__.py +++ b/twilio/rest/chat/v1/service/__init__.py @@ -1,1027 +1,1359 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 ServiceList(ListResource): - """ """ +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 - def __init__(self, version): + @property + def _proxy(self) -> "ServiceContext": """ - Initialize the ServiceList - - :param Version version: Version that contains the resource + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: twilio.rest.chat.v1.service.ServiceList - :rtype: twilio.rest.chat.v1.service.ServiceList + :returns: ServiceContext for this ServiceInstance """ - super(ServiceList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Services'.format(**self._solution) + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def create(self, friendly_name): + def delete(self) -> bool: """ - Create a new ServiceInstance + Deletes the ServiceInstance - :param unicode friendly_name: The friendly_name - :returns: Newly created ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({'FriendlyName': friendly_name, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return ServiceInstance(self._version, payload, ) + return self._proxy.delete() - def stream(self, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - 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. + Asynchronous coroutine that deletes the ServiceInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.ServiceInstance] + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the ServiceInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.ServiceInstance] + :returns: The fetched ServiceInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + 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": """ - Retrieve a single page of ServiceInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + Update the ServiceInstance - :returns: Page of ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServicePage + :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 """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + 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, ) - return ServicePage(self._version, response, self._solution) + 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, + ) - def get_page(self, target_url): + @property + def channels(self) -> ChannelList: """ - Retrieve a specific page of ServiceInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServicePage + Access the channels """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ServicePage(self._version, response, self._solution) + return self._proxy.channels - def get(self, sid): + @property + def roles(self) -> RoleList: """ - Constructs a ServiceContext - - :param sid: The sid - - :returns: twilio.rest.chat.v1.service.ServiceContext - :rtype: twilio.rest.chat.v1.service.ServiceContext + Access the roles """ - return ServiceContext(self._version, sid=sid, ) + return self._proxy.roles - def __call__(self, sid): + @property + def users(self) -> UserList: """ - Constructs a ServiceContext - - :param sid: The sid - - :returns: twilio.rest.chat.v1.service.ServiceContext - :rtype: twilio.rest.chat.v1.service.ServiceContext + Access the users """ - return ServiceContext(self._version, sid=sid, ) + return self._proxy.users - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ServicePage(Page): - """ """ +class ServiceContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the ServicePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the ServiceContext - :returns: twilio.rest.chat.v1.service.ServicePage - :rtype: twilio.rest.chat.v1.service.ServicePage + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. """ - super(ServicePage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) - def get_instance(self, payload): + self._channels: Optional[ChannelList] = None + self._roles: Optional[RoleList] = None + self._users: Optional[UserList] = None + + def delete(self) -> bool: """ - Build an instance of ServiceInstance + Deletes the ServiceInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v1.service.ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceInstance + :returns: True if delete succeeds, False otherwise """ - return ServiceInstance(self._version, payload, ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the ServiceInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class ServiceContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, sid): + def fetch(self) -> ServiceInstance: """ - Initialize the ServiceContext + Fetch the ServiceInstance - :param Version version: Version that contains the resource - :param sid: The sid - :returns: twilio.rest.chat.v1.service.ServiceContext - :rtype: twilio.rest.chat.v1.service.ServiceContext + :returns: The fetched ServiceInstance """ - super(ServiceContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Services/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - # Dependents - self._channels = None - self._roles = None - self._users = None + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: """ - Fetch a ServiceInstance + Asynchronous coroutine to fetch the ServiceInstance + - :returns: Fetched ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceInstance + :returns: The fetched ServiceInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) + headers = values.of({}) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" - def delete(self): - """ - Deletes the ServiceInstance + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def update(self, friendly_name=values.unset, - default_service_role_sid=values.unset, - default_channel_role_sid=values.unset, - default_channel_creator_role_sid=values.unset, - read_status_enabled=values.unset, reachability_enabled=values.unset, - typing_indicator_timeout=values.unset, - consumption_report_interval=values.unset, - notifications_new_message_enabled=values.unset, - notifications_new_message_template=values.unset, - notifications_added_to_channel_enabled=values.unset, - notifications_added_to_channel_template=values.unset, - notifications_removed_from_channel_enabled=values.unset, - notifications_removed_from_channel_template=values.unset, - notifications_invited_to_channel_enabled=values.unset, - notifications_invited_to_channel_template=values.unset, - pre_webhook_url=values.unset, post_webhook_url=values.unset, - webhook_method=values.unset, webhook_filters=values.unset, - webhooks_on_message_send_url=values.unset, - webhooks_on_message_send_method=values.unset, - webhooks_on_message_send_format=values.unset, - webhooks_on_message_update_url=values.unset, - webhooks_on_message_update_method=values.unset, - webhooks_on_message_update_format=values.unset, - webhooks_on_message_remove_url=values.unset, - webhooks_on_message_remove_method=values.unset, - webhooks_on_message_remove_format=values.unset, - webhooks_on_channel_add_url=values.unset, - webhooks_on_channel_add_method=values.unset, - webhooks_on_channel_add_format=values.unset, - webhooks_on_channel_destroy_url=values.unset, - webhooks_on_channel_destroy_method=values.unset, - webhooks_on_channel_destroy_format=values.unset, - webhooks_on_channel_update_url=values.unset, - webhooks_on_channel_update_method=values.unset, - webhooks_on_channel_update_format=values.unset, - webhooks_on_member_add_url=values.unset, - webhooks_on_member_add_method=values.unset, - webhooks_on_member_add_format=values.unset, - webhooks_on_member_remove_url=values.unset, - webhooks_on_member_remove_method=values.unset, - webhooks_on_member_remove_format=values.unset, - webhooks_on_message_sent_url=values.unset, - webhooks_on_message_sent_method=values.unset, - webhooks_on_message_sent_format=values.unset, - webhooks_on_message_updated_url=values.unset, - webhooks_on_message_updated_method=values.unset, - webhooks_on_message_updated_format=values.unset, - webhooks_on_message_removed_url=values.unset, - webhooks_on_message_removed_method=values.unset, - webhooks_on_message_removed_format=values.unset, - webhooks_on_channel_added_url=values.unset, - webhooks_on_channel_added_method=values.unset, - webhooks_on_channel_added_format=values.unset, - webhooks_on_channel_destroyed_url=values.unset, - webhooks_on_channel_destroyed_method=values.unset, - webhooks_on_channel_destroyed_format=values.unset, - webhooks_on_channel_updated_url=values.unset, - webhooks_on_channel_updated_method=values.unset, - webhooks_on_channel_updated_format=values.unset, - webhooks_on_member_added_url=values.unset, - webhooks_on_member_added_method=values.unset, - webhooks_on_member_added_format=values.unset, - webhooks_on_member_removed_url=values.unset, - webhooks_on_member_removed_method=values.unset, - webhooks_on_member_removed_format=values.unset, - limits_channel_members=values.unset, - limits_user_channels=values.unset): + 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 unicode friendly_name: The friendly_name - :param unicode default_service_role_sid: The default_service_role_sid - :param unicode default_channel_role_sid: The default_channel_role_sid - :param unicode default_channel_creator_role_sid: The default_channel_creator_role_sid - :param bool read_status_enabled: The read_status_enabled - :param bool reachability_enabled: The reachability_enabled - :param unicode typing_indicator_timeout: The typing_indicator_timeout - :param unicode consumption_report_interval: The consumption_report_interval - :param bool notifications_new_message_enabled: The notifications.new_message.enabled - :param unicode notifications_new_message_template: The notifications.new_message.template - :param bool notifications_added_to_channel_enabled: The notifications.added_to_channel.enabled - :param unicode notifications_added_to_channel_template: The notifications.added_to_channel.template - :param bool notifications_removed_from_channel_enabled: The notifications.removed_from_channel.enabled - :param unicode notifications_removed_from_channel_template: The notifications.removed_from_channel.template - :param bool notifications_invited_to_channel_enabled: The notifications.invited_to_channel.enabled - :param unicode notifications_invited_to_channel_template: The notifications.invited_to_channel.template - :param unicode pre_webhook_url: The pre_webhook_url - :param unicode post_webhook_url: The post_webhook_url - :param unicode webhook_method: The webhook_method - :param unicode webhook_filters: The webhook_filters - :param unicode webhooks_on_message_send_url: The webhooks.on_message_send.url - :param unicode webhooks_on_message_send_method: The webhooks.on_message_send.method - :param unicode webhooks_on_message_send_format: The webhooks.on_message_send.format - :param unicode webhooks_on_message_update_url: The webhooks.on_message_update.url - :param unicode webhooks_on_message_update_method: The webhooks.on_message_update.method - :param unicode webhooks_on_message_update_format: The webhooks.on_message_update.format - :param unicode webhooks_on_message_remove_url: The webhooks.on_message_remove.url - :param unicode webhooks_on_message_remove_method: The webhooks.on_message_remove.method - :param unicode webhooks_on_message_remove_format: The webhooks.on_message_remove.format - :param unicode webhooks_on_channel_add_url: The webhooks.on_channel_add.url - :param unicode webhooks_on_channel_add_method: The webhooks.on_channel_add.method - :param unicode webhooks_on_channel_add_format: The webhooks.on_channel_add.format - :param unicode webhooks_on_channel_destroy_url: The webhooks.on_channel_destroy.url - :param unicode webhooks_on_channel_destroy_method: The webhooks.on_channel_destroy.method - :param unicode webhooks_on_channel_destroy_format: The webhooks.on_channel_destroy.format - :param unicode webhooks_on_channel_update_url: The webhooks.on_channel_update.url - :param unicode webhooks_on_channel_update_method: The webhooks.on_channel_update.method - :param unicode webhooks_on_channel_update_format: The webhooks.on_channel_update.format - :param unicode webhooks_on_member_add_url: The webhooks.on_member_add.url - :param unicode webhooks_on_member_add_method: The webhooks.on_member_add.method - :param unicode webhooks_on_member_add_format: The webhooks.on_member_add.format - :param unicode webhooks_on_member_remove_url: The webhooks.on_member_remove.url - :param unicode webhooks_on_member_remove_method: The webhooks.on_member_remove.method - :param unicode webhooks_on_member_remove_format: The webhooks.on_member_remove.format - :param unicode webhooks_on_message_sent_url: The webhooks.on_message_sent.url - :param unicode webhooks_on_message_sent_method: The webhooks.on_message_sent.method - :param unicode webhooks_on_message_sent_format: The webhooks.on_message_sent.format - :param unicode webhooks_on_message_updated_url: The webhooks.on_message_updated.url - :param unicode webhooks_on_message_updated_method: The webhooks.on_message_updated.method - :param unicode webhooks_on_message_updated_format: The webhooks.on_message_updated.format - :param unicode webhooks_on_message_removed_url: The webhooks.on_message_removed.url - :param unicode webhooks_on_message_removed_method: The webhooks.on_message_removed.method - :param unicode webhooks_on_message_removed_format: The webhooks.on_message_removed.format - :param unicode webhooks_on_channel_added_url: The webhooks.on_channel_added.url - :param unicode webhooks_on_channel_added_method: The webhooks.on_channel_added.method - :param unicode webhooks_on_channel_added_format: The webhooks.on_channel_added.format - :param unicode webhooks_on_channel_destroyed_url: The webhooks.on_channel_destroyed.url - :param unicode webhooks_on_channel_destroyed_method: The webhooks.on_channel_destroyed.method - :param unicode webhooks_on_channel_destroyed_format: The webhooks.on_channel_destroyed.format - :param unicode webhooks_on_channel_updated_url: The webhooks.on_channel_updated.url - :param unicode webhooks_on_channel_updated_method: The webhooks.on_channel_updated.method - :param unicode webhooks_on_channel_updated_format: The webhooks.on_channel_updated.format - :param unicode webhooks_on_member_added_url: The webhooks.on_member_added.url - :param unicode webhooks_on_member_added_method: The webhooks.on_member_added.method - :param unicode webhooks_on_member_added_format: The webhooks.on_member_added.format - :param unicode webhooks_on_member_removed_url: The webhooks.on_member_removed.url - :param unicode webhooks_on_member_removed_method: The webhooks.on_member_removed.method - :param unicode webhooks_on_member_removed_format: The webhooks.on_member_removed.format - :param unicode limits_channel_members: The limits.channel_members - :param unicode limits_user_channels: The limits.user_channels - - :returns: Updated ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'DefaultServiceRoleSid': default_service_role_sid, - 'DefaultChannelRoleSid': default_channel_role_sid, - 'DefaultChannelCreatorRoleSid': default_channel_creator_role_sid, - 'ReadStatusEnabled': read_status_enabled, - 'ReachabilityEnabled': reachability_enabled, - 'TypingIndicatorTimeout': typing_indicator_timeout, - 'ConsumptionReportInterval': consumption_report_interval, - 'Notifications.NewMessage.Enabled': notifications_new_message_enabled, - 'Notifications.NewMessage.Template': notifications_new_message_template, - 'Notifications.AddedToChannel.Enabled': notifications_added_to_channel_enabled, - 'Notifications.AddedToChannel.Template': notifications_added_to_channel_template, - 'Notifications.RemovedFromChannel.Enabled': notifications_removed_from_channel_enabled, - 'Notifications.RemovedFromChannel.Template': notifications_removed_from_channel_template, - 'Notifications.InvitedToChannel.Enabled': 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.OnMessageSend.Format': webhooks_on_message_send_format, - 'Webhooks.OnMessageUpdate.Url': webhooks_on_message_update_url, - 'Webhooks.OnMessageUpdate.Method': webhooks_on_message_update_method, - 'Webhooks.OnMessageUpdate.Format': webhooks_on_message_update_format, - 'Webhooks.OnMessageRemove.Url': webhooks_on_message_remove_url, - 'Webhooks.OnMessageRemove.Method': webhooks_on_message_remove_method, - 'Webhooks.OnMessageRemove.Format': webhooks_on_message_remove_format, - 'Webhooks.OnChannelAdd.Url': webhooks_on_channel_add_url, - 'Webhooks.OnChannelAdd.Method': webhooks_on_channel_add_method, - 'Webhooks.OnChannelAdd.Format': webhooks_on_channel_add_format, - 'Webhooks.OnChannelDestroy.Url': webhooks_on_channel_destroy_url, - 'Webhooks.OnChannelDestroy.Method': webhooks_on_channel_destroy_method, - 'Webhooks.OnChannelDestroy.Format': webhooks_on_channel_destroy_format, - 'Webhooks.OnChannelUpdate.Url': webhooks_on_channel_update_url, - 'Webhooks.OnChannelUpdate.Method': webhooks_on_channel_update_method, - 'Webhooks.OnChannelUpdate.Format': webhooks_on_channel_update_format, - 'Webhooks.OnMemberAdd.Url': webhooks_on_member_add_url, - 'Webhooks.OnMemberAdd.Method': webhooks_on_member_add_method, - 'Webhooks.OnMemberAdd.Format': webhooks_on_member_add_format, - 'Webhooks.OnMemberRemove.Url': webhooks_on_member_remove_url, - 'Webhooks.OnMemberRemove.Method': webhooks_on_member_remove_method, - 'Webhooks.OnMemberRemove.Format': webhooks_on_member_remove_format, - 'Webhooks.OnMessageSent.Url': webhooks_on_message_sent_url, - 'Webhooks.OnMessageSent.Method': webhooks_on_message_sent_method, - 'Webhooks.OnMessageSent.Format': webhooks_on_message_sent_format, - 'Webhooks.OnMessageUpdated.Url': webhooks_on_message_updated_url, - 'Webhooks.OnMessageUpdated.Method': webhooks_on_message_updated_method, - 'Webhooks.OnMessageUpdated.Format': webhooks_on_message_updated_format, - 'Webhooks.OnMessageRemoved.Url': webhooks_on_message_removed_url, - 'Webhooks.OnMessageRemoved.Method': webhooks_on_message_removed_method, - 'Webhooks.OnMessageRemoved.Format': webhooks_on_message_removed_format, - 'Webhooks.OnChannelAdded.Url': webhooks_on_channel_added_url, - 'Webhooks.OnChannelAdded.Method': webhooks_on_channel_added_method, - 'Webhooks.OnChannelAdded.Format': webhooks_on_channel_added_format, - 'Webhooks.OnChannelDestroyed.Url': webhooks_on_channel_destroyed_url, - 'Webhooks.OnChannelDestroyed.Method': webhooks_on_channel_destroyed_method, - 'Webhooks.OnChannelDestroyed.Format': webhooks_on_channel_destroyed_format, - 'Webhooks.OnChannelUpdated.Url': webhooks_on_channel_updated_url, - 'Webhooks.OnChannelUpdated.Method': webhooks_on_channel_updated_method, - 'Webhooks.OnChannelUpdated.Format': webhooks_on_channel_updated_format, - 'Webhooks.OnMemberAdded.Url': webhooks_on_member_added_url, - 'Webhooks.OnMemberAdded.Method': webhooks_on_member_added_method, - 'Webhooks.OnMemberAdded.Format': webhooks_on_member_added_format, - 'Webhooks.OnMemberRemoved.Url': webhooks_on_member_removed_url, - 'Webhooks.OnMemberRemoved.Method': webhooks_on_member_removed_method, - 'Webhooks.OnMemberRemoved.Format': webhooks_on_member_removed_format, - 'Limits.ChannelMembers': limits_channel_members, - 'Limits.UserChannels': limits_user_channels, - }) + :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( - 'POST', - self._uri, - data=data, + 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'], ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) @property - def channels(self): + def channels(self) -> ChannelList: """ Access the channels - - :returns: twilio.rest.chat.v1.service.channel.ChannelList - :rtype: twilio.rest.chat.v1.service.channel.ChannelList """ if self._channels is None: - self._channels = ChannelList(self._version, service_sid=self._solution['sid'], ) + self._channels = ChannelList( + self._version, + self._solution["sid"], + ) return self._channels @property - def roles(self): + def roles(self) -> RoleList: """ Access the roles - - :returns: twilio.rest.chat.v1.service.role.RoleList - :rtype: twilio.rest.chat.v1.service.role.RoleList """ if self._roles is None: - self._roles = RoleList(self._version, service_sid=self._solution['sid'], ) + self._roles = RoleList( + self._version, + self._solution["sid"], + ) return self._roles @property - def users(self): + def users(self) -> UserList: """ Access the users - - :returns: twilio.rest.chat.v1.service.user.UserList - :rtype: twilio.rest.chat.v1.service.user.UserList """ if self._users is None: - self._users = UserList(self._version, service_sid=self._solution['sid'], ) + self._users = UserList( + self._version, + self._solution["sid"], + ) return self._users - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ServiceInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, sid=None): - """ - Initialize the ServiceInstance - - :returns: twilio.rest.chat.v1.service.ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceInstance - """ - super(ServiceInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'friendly_name': payload['friendly_name'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'default_service_role_sid': payload['default_service_role_sid'], - 'default_channel_role_sid': payload['default_channel_role_sid'], - 'default_channel_creator_role_sid': payload['default_channel_creator_role_sid'], - 'read_status_enabled': payload['read_status_enabled'], - 'reachability_enabled': payload['reachability_enabled'], - 'typing_indicator_timeout': deserialize.integer(payload['typing_indicator_timeout']), - 'consumption_report_interval': deserialize.integer(payload['consumption_report_interval']), - 'limits': payload['limits'], - 'webhooks': payload['webhooks'], - 'pre_webhook_url': payload['pre_webhook_url'], - 'post_webhook_url': payload['post_webhook_url'], - 'webhook_method': payload['webhook_method'], - 'webhook_filters': payload['webhook_filters'], - 'notifications': payload['notifications'], - 'url': payload['url'], - 'links': payload['links'], - } - - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } +class ServicePage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of ServiceInstance - :returns: ServiceContext for this ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = ServiceContext(self._version, sid=self._solution['sid'], ) - return self._context + return ServiceInstance(self._version, payload) - @property - def sid(self): + def __repr__(self) -> str: """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] +class ServiceList(ListResource): - @property - def date_updated(self): + def __init__(self, version: Version): """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + Initialize the ServiceList - @property - def default_service_role_sid(self): - """ - :returns: The default_service_role_sid - :rtype: unicode - """ - return self._properties['default_service_role_sid'] + :param version: Version that contains the resource - @property - def default_channel_role_sid(self): - """ - :returns: The default_channel_role_sid - :rtype: unicode """ - return self._properties['default_channel_role_sid'] + super().__init__(version) - @property - def default_channel_creator_role_sid(self): - """ - :returns: The default_channel_creator_role_sid - :rtype: unicode - """ - return self._properties['default_channel_creator_role_sid'] + self._uri = "/Services" - @property - def read_status_enabled(self): - """ - :returns: The read_status_enabled - :rtype: bool + def create(self, friendly_name: str) -> ServiceInstance: """ - return self._properties['read_status_enabled'] + Create the ServiceInstance - @property - def reachability_enabled(self): - """ - :returns: The reachability_enabled - :rtype: bool - """ - return self._properties['reachability_enabled'] + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - @property - def typing_indicator_timeout(self): + :returns: The created ServiceInstance """ - :returns: The typing_indicator_timeout - :rtype: unicode - """ - return self._properties['typing_indicator_timeout'] - @property - def consumption_report_interval(self): - """ - :returns: The consumption_report_interval - :rtype: unicode - """ - return self._properties['consumption_report_interval'] + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def limits(self): - """ - :returns: The limits - :rtype: dict - """ - return self._properties['limits'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def webhooks(self): - """ - :returns: The webhooks - :rtype: dict - """ - return self._properties['webhooks'] + headers["Accept"] = "application/json" - @property - def pre_webhook_url(self): - """ - :returns: The pre_webhook_url - :rtype: unicode - """ - return self._properties['pre_webhook_url'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def post_webhook_url(self): - """ - :returns: The post_webhook_url - :rtype: unicode - """ - return self._properties['post_webhook_url'] + return ServiceInstance(self._version, payload) - @property - def webhook_method(self): + async def create_async(self, friendly_name: str) -> ServiceInstance: """ - :returns: The webhook_method - :rtype: unicode - """ - return self._properties['webhook_method'] + Asynchronously create the ServiceInstance - @property - def webhook_filters(self): + :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 """ - :returns: The webhook_filters - :rtype: unicode + + 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]: """ - return self._properties['webhook_filters'] + 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. - @property - def notifications(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The notifications - :rtype: dict + 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]: """ - return self._properties['notifications'] + 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. - @property - def url(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The url - :rtype: unicode + 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]: """ - return self._properties['url'] + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def links(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The links - :rtype: unicode + 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]: """ - return self._properties['links'] + 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. - def fetch(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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: """ - Fetch a ServiceInstance + 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: Fetched ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceInstance + :returns: Page of ServiceInstance """ - return self._proxy.fetch() + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - def delete(self): + headers = values.of({"Content-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: """ - Deletes the ServiceInstance + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param page_token: PageToken provided by the API + :param page_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 """ - return self._proxy.delete() + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def update(self, friendly_name=values.unset, - default_service_role_sid=values.unset, - default_channel_role_sid=values.unset, - default_channel_creator_role_sid=values.unset, - read_status_enabled=values.unset, reachability_enabled=values.unset, - typing_indicator_timeout=values.unset, - consumption_report_interval=values.unset, - notifications_new_message_enabled=values.unset, - notifications_new_message_template=values.unset, - notifications_added_to_channel_enabled=values.unset, - notifications_added_to_channel_template=values.unset, - notifications_removed_from_channel_enabled=values.unset, - notifications_removed_from_channel_template=values.unset, - notifications_invited_to_channel_enabled=values.unset, - notifications_invited_to_channel_template=values.unset, - pre_webhook_url=values.unset, post_webhook_url=values.unset, - webhook_method=values.unset, webhook_filters=values.unset, - webhooks_on_message_send_url=values.unset, - webhooks_on_message_send_method=values.unset, - webhooks_on_message_send_format=values.unset, - webhooks_on_message_update_url=values.unset, - webhooks_on_message_update_method=values.unset, - webhooks_on_message_update_format=values.unset, - webhooks_on_message_remove_url=values.unset, - webhooks_on_message_remove_method=values.unset, - webhooks_on_message_remove_format=values.unset, - webhooks_on_channel_add_url=values.unset, - webhooks_on_channel_add_method=values.unset, - webhooks_on_channel_add_format=values.unset, - webhooks_on_channel_destroy_url=values.unset, - webhooks_on_channel_destroy_method=values.unset, - webhooks_on_channel_destroy_format=values.unset, - webhooks_on_channel_update_url=values.unset, - webhooks_on_channel_update_method=values.unset, - webhooks_on_channel_update_format=values.unset, - webhooks_on_member_add_url=values.unset, - webhooks_on_member_add_method=values.unset, - webhooks_on_member_add_format=values.unset, - webhooks_on_member_remove_url=values.unset, - webhooks_on_member_remove_method=values.unset, - webhooks_on_member_remove_format=values.unset, - webhooks_on_message_sent_url=values.unset, - webhooks_on_message_sent_method=values.unset, - webhooks_on_message_sent_format=values.unset, - webhooks_on_message_updated_url=values.unset, - webhooks_on_message_updated_method=values.unset, - webhooks_on_message_updated_format=values.unset, - webhooks_on_message_removed_url=values.unset, - webhooks_on_message_removed_method=values.unset, - webhooks_on_message_removed_format=values.unset, - webhooks_on_channel_added_url=values.unset, - webhooks_on_channel_added_method=values.unset, - webhooks_on_channel_added_format=values.unset, - webhooks_on_channel_destroyed_url=values.unset, - webhooks_on_channel_destroyed_method=values.unset, - webhooks_on_channel_destroyed_format=values.unset, - webhooks_on_channel_updated_url=values.unset, - webhooks_on_channel_updated_method=values.unset, - webhooks_on_channel_updated_format=values.unset, - webhooks_on_member_added_url=values.unset, - webhooks_on_member_added_method=values.unset, - webhooks_on_member_added_format=values.unset, - webhooks_on_member_removed_url=values.unset, - webhooks_on_member_removed_method=values.unset, - webhooks_on_member_removed_format=values.unset, - limits_channel_members=values.unset, - limits_user_channels=values.unset): + 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: """ - Update the ServiceInstance + 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 - :param unicode friendly_name: The friendly_name - :param unicode default_service_role_sid: The default_service_role_sid - :param unicode default_channel_role_sid: The default_channel_role_sid - :param unicode default_channel_creator_role_sid: The default_channel_creator_role_sid - :param bool read_status_enabled: The read_status_enabled - :param bool reachability_enabled: The reachability_enabled - :param unicode typing_indicator_timeout: The typing_indicator_timeout - :param unicode consumption_report_interval: The consumption_report_interval - :param bool notifications_new_message_enabled: The notifications.new_message.enabled - :param unicode notifications_new_message_template: The notifications.new_message.template - :param bool notifications_added_to_channel_enabled: The notifications.added_to_channel.enabled - :param unicode notifications_added_to_channel_template: The notifications.added_to_channel.template - :param bool notifications_removed_from_channel_enabled: The notifications.removed_from_channel.enabled - :param unicode notifications_removed_from_channel_template: The notifications.removed_from_channel.template - :param bool notifications_invited_to_channel_enabled: The notifications.invited_to_channel.enabled - :param unicode notifications_invited_to_channel_template: The notifications.invited_to_channel.template - :param unicode pre_webhook_url: The pre_webhook_url - :param unicode post_webhook_url: The post_webhook_url - :param unicode webhook_method: The webhook_method - :param unicode webhook_filters: The webhook_filters - :param unicode webhooks_on_message_send_url: The webhooks.on_message_send.url - :param unicode webhooks_on_message_send_method: The webhooks.on_message_send.method - :param unicode webhooks_on_message_send_format: The webhooks.on_message_send.format - :param unicode webhooks_on_message_update_url: The webhooks.on_message_update.url - :param unicode webhooks_on_message_update_method: The webhooks.on_message_update.method - :param unicode webhooks_on_message_update_format: The webhooks.on_message_update.format - :param unicode webhooks_on_message_remove_url: The webhooks.on_message_remove.url - :param unicode webhooks_on_message_remove_method: The webhooks.on_message_remove.method - :param unicode webhooks_on_message_remove_format: The webhooks.on_message_remove.format - :param unicode webhooks_on_channel_add_url: The webhooks.on_channel_add.url - :param unicode webhooks_on_channel_add_method: The webhooks.on_channel_add.method - :param unicode webhooks_on_channel_add_format: The webhooks.on_channel_add.format - :param unicode webhooks_on_channel_destroy_url: The webhooks.on_channel_destroy.url - :param unicode webhooks_on_channel_destroy_method: The webhooks.on_channel_destroy.method - :param unicode webhooks_on_channel_destroy_format: The webhooks.on_channel_destroy.format - :param unicode webhooks_on_channel_update_url: The webhooks.on_channel_update.url - :param unicode webhooks_on_channel_update_method: The webhooks.on_channel_update.method - :param unicode webhooks_on_channel_update_format: The webhooks.on_channel_update.format - :param unicode webhooks_on_member_add_url: The webhooks.on_member_add.url - :param unicode webhooks_on_member_add_method: The webhooks.on_member_add.method - :param unicode webhooks_on_member_add_format: The webhooks.on_member_add.format - :param unicode webhooks_on_member_remove_url: The webhooks.on_member_remove.url - :param unicode webhooks_on_member_remove_method: The webhooks.on_member_remove.method - :param unicode webhooks_on_member_remove_format: The webhooks.on_member_remove.format - :param unicode webhooks_on_message_sent_url: The webhooks.on_message_sent.url - :param unicode webhooks_on_message_sent_method: The webhooks.on_message_sent.method - :param unicode webhooks_on_message_sent_format: The webhooks.on_message_sent.format - :param unicode webhooks_on_message_updated_url: The webhooks.on_message_updated.url - :param unicode webhooks_on_message_updated_method: The webhooks.on_message_updated.method - :param unicode webhooks_on_message_updated_format: The webhooks.on_message_updated.format - :param unicode webhooks_on_message_removed_url: The webhooks.on_message_removed.url - :param unicode webhooks_on_message_removed_method: The webhooks.on_message_removed.method - :param unicode webhooks_on_message_removed_format: The webhooks.on_message_removed.format - :param unicode webhooks_on_channel_added_url: The webhooks.on_channel_added.url - :param unicode webhooks_on_channel_added_method: The webhooks.on_channel_added.method - :param unicode webhooks_on_channel_added_format: The webhooks.on_channel_added.format - :param unicode webhooks_on_channel_destroyed_url: The webhooks.on_channel_destroyed.url - :param unicode webhooks_on_channel_destroyed_method: The webhooks.on_channel_destroyed.method - :param unicode webhooks_on_channel_destroyed_format: The webhooks.on_channel_destroyed.format - :param unicode webhooks_on_channel_updated_url: The webhooks.on_channel_updated.url - :param unicode webhooks_on_channel_updated_method: The webhooks.on_channel_updated.method - :param unicode webhooks_on_channel_updated_format: The webhooks.on_channel_updated.format - :param unicode webhooks_on_member_added_url: The webhooks.on_member_added.url - :param unicode webhooks_on_member_added_method: The webhooks.on_member_added.method - :param unicode webhooks_on_member_added_format: The webhooks.on_member_added.format - :param unicode webhooks_on_member_removed_url: The webhooks.on_member_removed.url - :param unicode webhooks_on_member_removed_method: The webhooks.on_member_removed.method - :param unicode webhooks_on_member_removed_format: The webhooks.on_member_removed.format - :param unicode limits_channel_members: The limits.channel_members - :param unicode limits_user_channels: The limits.user_channels - - :returns: Updated ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceInstance + :returns: Page of 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_send_format=webhooks_on_message_send_format, - webhooks_on_message_update_url=webhooks_on_message_update_url, - webhooks_on_message_update_method=webhooks_on_message_update_method, - webhooks_on_message_update_format=webhooks_on_message_update_format, - webhooks_on_message_remove_url=webhooks_on_message_remove_url, - webhooks_on_message_remove_method=webhooks_on_message_remove_method, - webhooks_on_message_remove_format=webhooks_on_message_remove_format, - webhooks_on_channel_add_url=webhooks_on_channel_add_url, - webhooks_on_channel_add_method=webhooks_on_channel_add_method, - webhooks_on_channel_add_format=webhooks_on_channel_add_format, - webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, - webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, - webhooks_on_channel_destroy_format=webhooks_on_channel_destroy_format, - webhooks_on_channel_update_url=webhooks_on_channel_update_url, - webhooks_on_channel_update_method=webhooks_on_channel_update_method, - webhooks_on_channel_update_format=webhooks_on_channel_update_format, - webhooks_on_member_add_url=webhooks_on_member_add_url, - webhooks_on_member_add_method=webhooks_on_member_add_method, - webhooks_on_member_add_format=webhooks_on_member_add_format, - webhooks_on_member_remove_url=webhooks_on_member_remove_url, - webhooks_on_member_remove_method=webhooks_on_member_remove_method, - webhooks_on_member_remove_format=webhooks_on_member_remove_format, - webhooks_on_message_sent_url=webhooks_on_message_sent_url, - webhooks_on_message_sent_method=webhooks_on_message_sent_method, - webhooks_on_message_sent_format=webhooks_on_message_sent_format, - webhooks_on_message_updated_url=webhooks_on_message_updated_url, - webhooks_on_message_updated_method=webhooks_on_message_updated_method, - webhooks_on_message_updated_format=webhooks_on_message_updated_format, - webhooks_on_message_removed_url=webhooks_on_message_removed_url, - webhooks_on_message_removed_method=webhooks_on_message_removed_method, - webhooks_on_message_removed_format=webhooks_on_message_removed_format, - webhooks_on_channel_added_url=webhooks_on_channel_added_url, - webhooks_on_channel_added_method=webhooks_on_channel_added_method, - webhooks_on_channel_added_format=webhooks_on_channel_added_format, - webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, - webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, - webhooks_on_channel_destroyed_format=webhooks_on_channel_destroyed_format, - webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, - webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, - webhooks_on_channel_updated_format=webhooks_on_channel_updated_format, - webhooks_on_member_added_url=webhooks_on_member_added_url, - webhooks_on_member_added_method=webhooks_on_member_added_method, - webhooks_on_member_added_format=webhooks_on_member_added_format, - webhooks_on_member_removed_url=webhooks_on_member_removed_url, - webhooks_on_member_removed_method=webhooks_on_member_removed_method, - webhooks_on_member_removed_format=webhooks_on_member_removed_format, - limits_channel_members=limits_channel_members, - limits_user_channels=limits_user_channels, - ) + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) - @property - def channels(self): + async def get_page_async(self, target_url: str) -> ServicePage: """ - Access the channels + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately - :returns: twilio.rest.chat.v1.service.channel.ChannelList - :rtype: twilio.rest.chat.v1.service.channel.ChannelList + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance """ - return self._proxy.channels + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) - @property - def roles(self): + def get(self, sid: str) -> ServiceContext: """ - Access the roles + Constructs a ServiceContext - :returns: twilio.rest.chat.v1.service.role.RoleList - :rtype: twilio.rest.chat.v1.service.role.RoleList + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. """ - return self._proxy.roles + return ServiceContext(self._version, sid=sid) - @property - def users(self): + def __call__(self, sid: str) -> ServiceContext: """ - Access the users + Constructs a ServiceContext - :returns: twilio.rest.chat.v1.service.user.UserList - :rtype: twilio.rest.chat.v1.service.user.UserList + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. """ - return self._proxy.users + return ServiceContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/chat/v1/service/channel/__init__.py b/twilio/rest/chat/v1/service/channel/__init__.py index 48e84249c2..ffe42c0b5d 100644 --- a/twilio/rest/chat/v1/service/channel/__init__.py +++ b/twilio/rest/chat/v1/service/channel/__init__.py @@ -1,616 +1,790 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 ChannelList(ListResource): - """ """ +class ChannelInstance(InstanceResource): - def __init__(self, version, service_sid): - """ - Initialize the ChannelList + 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") - :param Version version: Version that contains the resource - :param service_sid: The service_sid + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ChannelContext] = None - :returns: twilio.rest.chat.v1.service.channel.ChannelList - :rtype: twilio.rest.chat.v1.service.channel.ChannelList + @property + def _proxy(self) -> "ChannelContext": """ - super(ChannelList, self).__init__(version) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Channels'.format(**self._solution) + :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 create(self, friendly_name=values.unset, unique_name=values.unset, - attributes=values.unset, type=values.unset): + def delete(self) -> bool: """ - Create a new ChannelInstance + Deletes the ChannelInstance - :param unicode friendly_name: The friendly_name - :param unicode unique_name: The unique_name - :param unicode attributes: The attributes - :param ChannelInstance.ChannelType type: The type - :returns: Newly created ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'FriendlyName': friendly_name, - 'UniqueName': unique_name, - 'Attributes': attributes, - 'Type': type, - }) + return self._proxy.delete() - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelInstance - return ChannelInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, type=values.unset, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + return await self._proxy.delete_async() - :param ChannelInstance.ChannelType type: The type - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.channel.ChannelInstance] + def fetch(self) -> "ChannelInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the ChannelInstance - page = self.page(type=type, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched ChannelInstance + """ + return self._proxy.fetch() - def list(self, type=values.unset, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the ChannelInstance - :param ChannelInstance.ChannelType type: The type - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.channel.ChannelInstance] + :returns: The fetched ChannelInstance """ - return list(self.stream(type=type, limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, type=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "ChannelInstance": """ - Retrieve a single page of ChannelInstance records from the API. - Request is executed immediately + Update the ChannelInstance - :param ChannelInstance.ChannelType type: The type - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :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: Page of ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelPage + :returns: The updated ChannelInstance """ - params = values.of({ - 'Type': serialize.map(type, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + return self._proxy.update( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, ) - return ChannelPage(self._version, response, self._solution) - - def get_page(self, target_url): + 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": """ - Retrieve a specific page of ChannelInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the ChannelInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelPage + :returns: The updated ChannelInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, ) - return ChannelPage(self._version, response, self._solution) - - def get(self, sid): + @property + def invites(self) -> InviteList: """ - Constructs a ChannelContext - - :param sid: The sid - - :returns: twilio.rest.chat.v1.service.channel.ChannelContext - :rtype: twilio.rest.chat.v1.service.channel.ChannelContext + Access the invites """ - return ChannelContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.invites - def __call__(self, sid): + @property + def members(self) -> MemberList: """ - Constructs a ChannelContext - - :param sid: The sid + Access the members + """ + return self._proxy.members - :returns: twilio.rest.chat.v1.service.channel.ChannelContext - :rtype: twilio.rest.chat.v1.service.channel.ChannelContext + @property + def messages(self) -> MessageList: """ - return ChannelContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Access the messages + """ + return self._proxy.messages - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ChannelPage(Page): - """ """ +class ChannelContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the ChannelPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid + Initialize the ChannelContext - :returns: twilio.rest.chat.v1.service.channel.ChannelPage - :rtype: twilio.rest.chat.v1.service.channel.ChannelPage + :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(ChannelPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Channels/{sid}".format(**self._solution) - def get_instance(self, payload): + self._invites: Optional[InviteList] = None + self._members: Optional[MemberList] = None + self._messages: Optional[MessageList] = None + + def delete(self) -> bool: """ - Build an instance of ChannelInstance + Deletes the ChannelInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v1.service.channel.ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance + :returns: True if delete succeeds, False otherwise """ - return ChannelInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the ChannelInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class ChannelContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, service_sid, sid): + def fetch(self) -> ChannelInstance: """ - Initialize the ChannelContext + Fetch the ChannelInstance - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: The sid - :returns: twilio.rest.chat.v1.service.channel.ChannelContext - :rtype: twilio.rest.chat.v1.service.channel.ChannelContext + :returns: The fetched ChannelInstance """ - super(ChannelContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Channels/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - # Dependents - self._members = None - self._messages = None - self._invites = None + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - def fetch(self): + async def fetch_async(self) -> ChannelInstance: """ - Fetch a ChannelInstance + Asynchronous coroutine to fetch the ChannelInstance + - :returns: Fetched ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance + :returns: The fetched ChannelInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + def update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ChannelInstance: """ - Deletes the ChannelInstance + Update the ChannelInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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._version.delete('delete', self._uri) - def update(self, friendly_name=values.unset, unique_name=values.unset, - attributes=values.unset): + 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: """ - Update the ChannelInstance + Asynchronous coroutine to update the ChannelInstance - :param unicode friendly_name: The friendly_name - :param unicode unique_name: The unique_name - :param unicode attributes: The attributes + :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: Updated ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance + :returns: The updated ChannelInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'UniqueName': unique_name, - 'Attributes': attributes, - }) - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) @property - def members(self): + def invites(self) -> InviteList: """ - Access the members + Access the invites + """ + if self._invites is None: + self._invites = InviteList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._invites - :returns: twilio.rest.chat.v1.service.channel.member.MemberList - :rtype: twilio.rest.chat.v1.service.channel.member.MemberList + @property + def members(self) -> MemberList: + """ + Access the members """ if self._members is None: self._members = MemberList( self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) return self._members @property - def messages(self): + def messages(self) -> MessageList: """ Access the messages - - :returns: twilio.rest.chat.v1.service.channel.message.MessageList - :rtype: twilio.rest.chat.v1.service.channel.message.MessageList """ if self._messages is None: self._messages = MessageList( self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) return self._messages - @property - def invites(self): + def __repr__(self) -> str: """ - Access the invites + Provide a friendly representation - :returns: twilio.rest.chat.v1.service.channel.invite.InviteList - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteList + :returns: Machine friendly representation """ - if self._invites is None: - self._invites = InviteList( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['sid'], - ) - return self._invites + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" -class ChannelInstance(InstanceResource): - """ """ - - class ChannelType(object): - PUBLIC = "public" - PRIVATE = "private" +class ChannelList(ListResource): - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the ChannelInstance - - :returns: twilio.rest.chat.v1.service.channel.ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance - """ - super(ChannelInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'friendly_name': payload['friendly_name'], - 'unique_name': payload['unique_name'], - 'attributes': payload['attributes'], - 'type': payload['type'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'created_by': payload['created_by'], - 'members_count': deserialize.integer(payload['members_count']), - 'messages_count': deserialize.integer(payload['messages_count']), - 'url': payload['url'], - 'links': payload['links'], - } + def __init__(self, version: Version, service_sid: str): + """ + Initialize the ChannelList - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + :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. - @property - def _proxy(self): """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + super().__init__(version) - :returns: ChannelContext for this ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelContext - """ - if self._context is None: - self._context = ChannelContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Channels".format(**self._solution) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + 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: """ - return self._properties['sid'] + Create the ChannelInstance - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + :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: - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode + :returns: The created ChannelInstance """ - return self._properties['service_sid'] - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "Type": type, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def unique_name(self): - """ - :returns: The unique_name - :rtype: unicode - """ - return self._properties['unique_name'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def attributes(self): - """ - :returns: The attributes - :rtype: unicode - """ - return self._properties['attributes'] + headers["Accept"] = "application/json" - @property - def type(self): - """ - :returns: The type - :rtype: ChannelInstance.ChannelType - """ - return self._properties['type'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def date_updated(self): + 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: """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + Asynchronously create the ChannelInstance - @property - def created_by(self): - """ - :returns: The created_by - :rtype: unicode - """ - return self._properties['created_by'] + :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: - @property - def members_count(self): + :returns: The created ChannelInstance """ - :returns: The members_count - :rtype: unicode - """ - return self._properties['members_count'] - @property - def messages_count(self): + 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]: """ - :returns: The messages_count - :rtype: unicode + 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 """ - return self._properties['messages_count'] + limits = self._version.read_limits(limit, page_size) + page = self.page(type=type, page_size=limits["page_size"]) - @property - def url(self): + 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]: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(type=type, page_size=limits["page_size"]) - @property - def links(self): + 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]: """ - :returns: The links - :rtype: unicode + 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]: """ - return self._properties['links'] + 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 fetch(self): + 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: """ - Fetch a ChannelInstance + Retrieve a single page of ChannelInstance records from the API. + Request is executed immediately - :returns: Fetched ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance + :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 """ - return self._proxy.fetch() + 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"}) - def delete(self): + 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: """ - Deletes the ChannelInstance + Asynchronously retrieve a single page of ChannelInstance records from the API. + Request is executed immediately - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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 """ - return self._proxy.delete() + 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" - def update(self, friendly_name=values.unset, unique_name=values.unset, - attributes=values.unset): + 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: """ - Update the ChannelInstance + Retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately - :param unicode friendly_name: The friendly_name - :param unicode unique_name: The unique_name - :param unicode attributes: The attributes + :param target_url: API-generated URL for the requested results page - :returns: Updated ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance + :returns: Page of ChannelInstance """ - return self._proxy.update( - friendly_name=friendly_name, - unique_name=unique_name, - attributes=attributes, - ) + response = self._version.domain.twilio.request("GET", target_url) + return ChannelPage(self._version, response, self._solution) - @property - def members(self): + async def get_page_async(self, target_url: str) -> ChannelPage: """ - Access the members + Asynchronously retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately - :returns: twilio.rest.chat.v1.service.channel.member.MemberList - :rtype: twilio.rest.chat.v1.service.channel.member.MemberList + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance """ - return self._proxy.members + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelPage(self._version, response, self._solution) - @property - def messages(self): + def get(self, sid: str) -> ChannelContext: """ - Access the messages + Constructs a ChannelContext - :returns: twilio.rest.chat.v1.service.channel.message.MessageList - :rtype: twilio.rest.chat.v1.service.channel.message.MessageList + :param sid: The Twilio-provided string that uniquely identifies the Channel resource to update. """ - return self._proxy.messages + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - @property - def invites(self): + def __call__(self, sid: str) -> ChannelContext: """ - Access the invites + Constructs a ChannelContext - :returns: twilio.rest.chat.v1.service.channel.invite.InviteList - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteList + :param sid: The Twilio-provided string that uniquely identifies the Channel resource to update. """ - return self._proxy.invites + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/chat/v1/service/channel/invite.py b/twilio/rest/chat/v1/service/channel/invite.py index f12f4fef4a..e5cd4ebe36 100644 --- a/twilio/rest/chat/v1/service/channel/invite.py +++ b/twilio/rest/chat/v1/service/channel/invite.py @@ -1,462 +1,598 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 InviteList(ListResource): - """ """ +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 - def __init__(self, version, service_sid, channel_sid): + @property + def _proxy(self) -> "InviteContext": """ - Initialize the InviteList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param channel_sid: The channel_sid + :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 - :returns: twilio.rest.chat.v1.service.channel.invite.InviteList - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteList + def delete(self) -> bool: """ - super(InviteList, self).__init__(version) + Deletes the InviteInstance - # 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, role_sid=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create a new InviteInstance - - :param unicode identity: The identity - :param unicode role_sid: The role_sid + return self._proxy.delete() - :returns: Newly created InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteInstance + async def delete_async(self) -> bool: """ - data = values.of({'Identity': identity, 'RoleSid': role_sid, }) + Asynchronous coroutine that deletes the InviteInstance - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - return InviteInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - ) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def stream(self, identity=values.unset, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the InviteInstance - :param unicode identity: The identity - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.channel.invite.InviteInstance] + :returns: The fetched InviteInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(identity=identity, page_size=limits['page_size'], ) + async def fetch_async(self) -> "InviteInstance": + """ + Asynchronous coroutine to fetch the InviteInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, identity=values.unset, limit=None, page_size=None): + :returns: The fetched 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 unicode identity: The identity - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + return await self._proxy.fetch_async() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.channel.invite.InviteInstance] + def __repr__(self) -> str: """ - return list(self.stream(identity=identity, limit=limit, page_size=page_size, )) + Provide a friendly representation - def page(self, identity=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + :returns: Machine friendly representation """ - Retrieve a single page of InviteInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param unicode identity: The identity - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InvitePage +class InviteContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ - params = values.of({ - 'Identity': serialize.map(identity, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Initialize the InviteContext - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + :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) - return InvitePage(self._version, response, self._solution) + # 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 get_page(self, target_url): + def delete(self) -> bool: """ - Retrieve a specific page of InviteInstance records from the API. - Request is executed immediately + Deletes the InviteInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InvitePage + :returns: True if delete succeeds, False otherwise """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return InvitePage(self._version, response, self._solution) + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def get(self, sid): + async def delete_async(self) -> bool: """ - Constructs a InviteContext + Asynchronous coroutine that deletes the InviteInstance - :param sid: The sid - :returns: twilio.rest.chat.v1.service.channel.invite.InviteContext - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteContext + :returns: True if delete succeeds, False otherwise """ - return InviteContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers ) - def __call__(self, sid): + def fetch(self) -> InviteInstance: """ - Constructs a InviteContext + Fetch the InviteInstance - :param sid: The sid - :returns: twilio.rest.chat.v1.service.channel.invite.InviteContext - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteContext + :returns: The fetched InviteInstance """ - return InviteContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InviteInstance( self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + async def fetch_async(self) -> InviteInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the InviteInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched InviteInstance """ - return '' + headers = values.of({}) -class InvitePage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): - """ - Initialize the InvitePage + 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"], + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :param channel_sid: The channel_sid + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.chat.v1.service.channel.invite.InvitePage - :rtype: twilio.rest.chat.v1.service.channel.invite.InvitePage + :returns: Machine friendly representation """ - super(InvitePage, self).__init__(version, response) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Path Solution - self._solution = solution - def get_instance(self, payload): +class InvitePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: """ Build an instance of InviteInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.chat.v1.service.channel.invite.InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.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'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class InviteContext(InstanceContext): - """ """ +class InviteList(ListResource): - def __init__(self, version, service_sid, channel_sid, sid): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ - Initialize the InviteContext + Initialize the InviteList - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param channel_sid: The channel_sid - :param sid: The sid + :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. - :returns: twilio.rest.chat.v1.service.channel.invite.InviteContext - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteContext """ - super(InviteContext, self).__init__(version) + 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) + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Invites".format( + **self._solution + ) - def fetch(self): + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: """ - Fetch a 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: Fetched InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteInstance + :returns: The created InviteInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def delete(self): + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: """ - Deletes the InviteInstance + Asynchronously create the InviteInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :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. - def __repr__(self): + :returns: The created InviteInstance """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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" -class InviteInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - def __init__(self, version, payload, service_sid, channel_sid, sid=None): + 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]: """ - Initialize the 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: twilio.rest.chat.v1.service.channel.invite.InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteInstance + :returns: Generator that will yield up to limit results """ - super(InviteInstance, self).__init__(version) + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'channel_sid': payload['channel_sid'], - 'service_sid': payload['service_sid'], - 'identity': payload['identity'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'role_sid': payload['role_sid'], - 'created_by': payload['created_by'], - 'url': payload['url'], - } + return self._version.stream(page, limits["limit"]) - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], - } + 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. - @property - def _proxy(self): + :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 """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) - :returns: InviteContext for this InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteContext + 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]: """ - 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'], + 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, ) - return self._context + ) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: """ - return self._properties['sid'] + 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. - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + :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, + ) + ] - @property - def channel_sid(self): - """ - :returns: The channel_sid - :rtype: unicode + 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: """ - return self._properties['channel_sid'] + Retrieve a single page of InviteInstance records from the API. + Request is executed immediately - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] + :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 - @property - def identity(self): - """ - :returns: The identity - :rtype: unicode + :returns: Page of InviteInstance """ - return self._properties['identity'] + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Accept"] = "application/json" - @property - def role_sid(self): + 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: """ - :returns: The role_sid - :rtype: unicode + 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 """ - return self._properties['role_sid'] + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def created_by(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The created_by - :rtype: unicode + 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 """ - return self._properties['created_by'] + response = self._version.domain.twilio.request("GET", target_url) + return InvitePage(self._version, response, self._solution) - @property - def url(self): + async def get_page_async(self, target_url: str) -> InvitePage: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return InvitePage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> InviteContext: """ - Fetch a InviteInstance + Constructs a InviteContext - :returns: Fetched InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteInstance + :param sid: The Twilio-provided string that uniquely identifies the Invite resource to fetch. """ - return self._proxy.fetch() + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - def delete(self): + def __call__(self, sid: str) -> InviteContext: """ - Deletes the InviteInstance + Constructs a InviteContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the Invite resource to fetch. """ - return self._proxy.delete() + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/chat/v1/service/channel/member.py b/twilio/rest/chat/v1/service/channel/member.py index 30a3f0767b..1262703ddc 100644 --- a/twilio/rest/chat/v1/service/channel/member.py +++ b/twilio/rest/chat/v1/service/channel/member.py @@ -1,514 +1,716 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 MemberList(ListResource): - """ """ +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 - def __init__(self, version, service_sid, channel_sid): + @property + def _proxy(self) -> "MemberContext": """ - Initialize the MemberList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param channel_sid: The channel_sid + :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 - :returns: twilio.rest.chat.v1.service.channel.member.MemberList - :rtype: twilio.rest.chat.v1.service.channel.member.MemberList + def delete(self) -> bool: """ - super(MemberList, self).__init__(version) + Deletes the MemberInstance - # 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, role_sid=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create a new MemberInstance + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MemberInstance - :param unicode identity: The identity - :param unicode role_sid: The role_sid - :returns: Newly created MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({'Identity': identity, 'RoleSid': role_sid, }) + return await self._proxy.delete_async() - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + def fetch(self) -> "MemberInstance": + """ + Fetch the MemberInstance - return MemberInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - ) - def stream(self, identity=values.unset, limit=None, page_size=None): + :returns: The fetched 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. + return self._proxy.fetch() - :param unicode identity: The identity - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + async def fetch_async(self) -> "MemberInstance": + """ + Asynchronous coroutine to fetch the MemberInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.channel.member.MemberInstance] + + :returns: The fetched MemberInstance """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.fetch_async() - page = self.page(identity=identity, page_size=limits['page_size'], ) + def update( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> "MemberInstance": + """ + Update the MemberInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) + :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). - def list(self, identity=values.unset, limit=None, page_size=None): + :returns: The updated 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. + return self._proxy.update( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + ) - :param unicode identity: The identity - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + 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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.channel.member.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 list(self.stream(identity=identity, limit=limit, page_size=page_size, )) + return await self._proxy.update_async( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + ) - def page(self, identity=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def __repr__(self) -> str: """ - Retrieve a single page of MemberInstance records from the API. - Request is executed immediately + Provide a friendly representation - :param unicode identity: The identity - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: Page of MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberPage + +class MemberContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ - params = values.of({ - 'Identity': serialize.map(identity, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Initialize the MemberContext - response = self._version.page( - 'GET', - self._uri, - params=params, + :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 + ) ) - return MemberPage(self._version, response, self._solution) + def delete(self) -> bool: + """ + Deletes the MemberInstance - def get_page(self, target_url): + + :returns: True if delete succeeds, False otherwise """ - Retrieve a specific page of MemberInstance records from the API. - Request is executed immediately - :param str target_url: API-generated URL for the requested results page + headers = values.of({}) - :returns: Page of MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberPage + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Asynchronous coroutine that deletes the MemberInstance - return MemberPage(self._version, response, self._solution) - def get(self, sid): + :returns: True if delete succeeds, False otherwise """ - Constructs a MemberContext - :param sid: The sid + headers = values.of({}) - :returns: twilio.rest.chat.v1.service.channel.member.MemberContext - :rtype: twilio.rest.chat.v1.service.channel.member.MemberContext + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MemberInstance: """ - return MemberContext( + 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, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - def __call__(self, sid): + async def fetch_async(self) -> MemberInstance: """ - Constructs a MemberContext + Asynchronous coroutine to fetch the MemberInstance - :param sid: The sid - :returns: twilio.rest.chat.v1.service.channel.member.MemberContext - :rtype: twilio.rest.chat.v1.service.channel.member.MemberContext + :returns: The fetched MemberInstance """ - return MemberContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MemberInstance( self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + def update( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> MemberInstance: """ - Provide a friendly representation + Update the MemberInstance - :returns: Machine friendly representation - :rtype: str + :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 '' + data = values.of( + { + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" -class MemberPage(Page): - """ """ + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) - def __init__(self, version, response, solution): + 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: """ - Initialize the MemberPage + Asynchronous coroutine to update the MemberInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :param channel_sid: The channel_sid + :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: twilio.rest.chat.v1.service.channel.member.MemberPage - :rtype: twilio.rest.chat.v1.service.channel.member.MemberPage + :returns: The updated MemberInstance """ - super(MemberPage, self).__init__(version, response) - # Path Solution - self._solution = solution + 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 get_instance(self, payload): + def __repr__(self) -> str: """ - Build an instance of MemberInstance + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v1.service.channel.member.MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance +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'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class MemberContext(InstanceContext): - """ """ +class MemberList(ListResource): - def __init__(self, version, service_sid, channel_sid, sid): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ - Initialize the MemberContext + Initialize the MemberList - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param channel_sid: The channel_sid - :param sid: The sid + :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. - :returns: twilio.rest.chat.v1.service.channel.member.MemberContext - :rtype: twilio.rest.chat.v1.service.channel.member.MemberContext """ - super(MemberContext, self).__init__(version) + 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) + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Members".format( + **self._solution + ) - def fetch(self): + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> MemberInstance: """ - Fetch a MemberInstance + Create the MemberInstance - :returns: Fetched MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.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 """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def delete(self): + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> MemberInstance: """ - Deletes the MemberInstance + Asynchronously create the MemberInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :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). - def update(self, role_sid=values.unset, - last_consumed_message_index=values.unset): + :returns: The created MemberInstance """ - Update the MemberInstance - :param unicode role_sid: The role_sid - :param unicode last_consumed_message_index: The last_consumed_message_index + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: Updated MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance - """ - data = values.of({'RoleSid': role_sid, 'LastConsumedMessageIndex': last_consumed_message_index, }) + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def __repr__(self): + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MemberInstance]: """ - Provide a friendly representation + 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. - :returns: Machine friendly representation - :rtype: str + :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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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"]) -class MemberInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, service_sid, channel_sid, sid=None): - """ - Initialize the MemberInstance - - :returns: twilio.rest.chat.v1.service.channel.member.MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance - """ - super(MemberInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'channel_sid': payload['channel_sid'], - 'service_sid': payload['service_sid'], - 'identity': payload['identity'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'role_sid': payload['role_sid'], - 'last_consumed_message_index': deserialize.integer(payload['last_consumed_message_index']), - 'last_consumption_timestamp': deserialize.iso8601_datetime(payload['last_consumption_timestamp']), - 'url': payload['url'], - } + 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. - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], - } + :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) - @property - def _proxy(self): + :returns: Generator that will yield up to limit results """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) - :returns: MemberContext for this MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberContext + 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]: """ - 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'], + 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, ) - return self._context + ) - @property - def sid(self): + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + 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. - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + :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, + ) + ] - @property - def channel_sid(self): - """ - :returns: The channel_sid - :rtype: unicode + 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: """ - return self._properties['channel_sid'] + Retrieve a single page of MemberInstance records from the API. + Request is executed immediately - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] + :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 - @property - def identity(self): - """ - :returns: The identity - :rtype: unicode + :returns: Page of MemberInstance """ - return self._properties['identity'] + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Accept"] = "application/json" - @property - def role_sid(self): - """ - :returns: The role_sid - :rtype: unicode - """ - return self._properties['role_sid'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, self._solution) - @property - def last_consumed_message_index(self): - """ - :returns: The last_consumed_message_index - :rtype: unicode + 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: """ - return self._properties['last_consumed_message_index'] + Asynchronously retrieve a single page of MemberInstance records from the API. + Request is executed immediately - @property - def last_consumption_timestamp(self): - """ - :returns: The last_consumption_timestamp - :rtype: datetime - """ - return self._properties['last_consumption_timestamp'] + :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 - @property - def url(self): + :returns: Page of MemberInstance """ - :returns: The url - :rtype: unicode + 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: """ - return self._properties['url'] + Retrieve a specific page of MemberInstance records from the API. + Request is executed immediately - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance """ - Fetch a MemberInstance + response = self._version.domain.twilio.request("GET", target_url) + return MemberPage(self._version, response, self._solution) - :returns: Fetched MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance + async def get_page_async(self, target_url: str) -> MemberPage: """ - return self._proxy.fetch() + 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 - def delete(self): + :returns: Page of MemberInstance """ - Deletes the MemberInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return MemberPage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def get(self, sid: str) -> MemberContext: """ - return self._proxy.delete() + Constructs a MemberContext - def update(self, role_sid=values.unset, - last_consumed_message_index=values.unset): + :param sid: The Twilio-provided string that uniquely identifies the Member resource to update. """ - Update the MemberInstance + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - :param unicode role_sid: The role_sid - :param unicode last_consumed_message_index: The last_consumed_message_index + def __call__(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext - :returns: Updated MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance + :param sid: The Twilio-provided string that uniquely identifies the Member resource to update. """ - return self._proxy.update( - role_sid=role_sid, - last_consumed_message_index=last_consumed_message_index, + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/chat/v1/service/channel/message.py b/twilio/rest/chat/v1/service/channel/message.py index 44d947bcd6..e7cfc9217d 100644 --- a/twilio/rest/chat/v1/service/channel/message.py +++ b/twilio/rest/chat/v1/service/channel/message.py @@ -1,531 +1,731 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 MessageList(ListResource): - """ """ +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") - def __init__(self, version, service_sid, channel_sid): + 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": """ - Initialize the MessageList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param channel_sid: The channel_sid + :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 - :returns: twilio.rest.chat.v1.service.channel.message.MessageList - :rtype: twilio.rest.chat.v1.service.channel.message.MessageList + def delete(self) -> bool: """ - super(MessageList, self).__init__(version) + Deletes the MessageInstance - # 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, from_=values.unset, attributes=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create a new MessageInstance + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance - :param unicode body: The body - :param unicode from_: The from - :param unicode attributes: The attributes - :returns: Newly created MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({'Body': body, 'From': from_, 'Attributes': attributes, }) + return await self._proxy.delete_async() - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + def fetch(self) -> "MessageInstance": + """ + Fetch the MessageInstance - return MessageInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - ) - def stream(self, order=values.unset, limit=None, page_size=None): + :returns: The fetched 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. + return self._proxy.fetch() - :param MessageInstance.OrderType order: The order - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + async def fetch_async(self) -> "MessageInstance": + """ + Asynchronous coroutine to fetch the MessageInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.channel.message.MessageInstance] + + :returns: The fetched MessageInstance """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.fetch_async() - page = self.page(order=order, page_size=limits['page_size'], ) + def update( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Update the MessageInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) + :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. - def list(self, order=values.unset, limit=None, page_size=None): + :returns: The updated 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. + return self._proxy.update( + body=body, + attributes=attributes, + ) - :param MessageInstance.OrderType order: The order - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + async def update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Asynchronous coroutine to update the MessageInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.channel.message.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 list(self.stream(order=order, limit=limit, page_size=page_size, )) + return await self._proxy.update_async( + body=body, + attributes=attributes, + ) - def page(self, order=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def __repr__(self) -> str: """ - Retrieve a single page of MessageInstance records from the API. - Request is executed immediately + Provide a friendly representation - :param MessageInstance.OrderType order: The order - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: Page of MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessagePage + +class MessageContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ - params = values.of({ - 'Order': order, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Initialize the MessageContext - response = self._version.page( - 'GET', - self._uri, - params=params, + :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 + ) ) - return MessagePage(self._version, response, self._solution) + def delete(self) -> bool: + """ + Deletes the MessageInstance - def get_page(self, target_url): + + :returns: True if delete succeeds, False otherwise """ - Retrieve a specific page of MessageInstance records from the API. - Request is executed immediately - :param str target_url: API-generated URL for the requested results page + headers = values.of({}) - :returns: Page of MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessagePage + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Asynchronous coroutine that deletes the MessageInstance - return MessagePage(self._version, response, self._solution) - def get(self, sid): + :returns: True if delete succeeds, False otherwise """ - Constructs a MessageContext - :param sid: The sid + headers = values.of({}) - :returns: twilio.rest.chat.v1.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v1.service.channel.message.MessageContext + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: """ - return MessageContext( + 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, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - def __call__(self, sid): + async def fetch_async(self) -> MessageInstance: """ - Constructs a MessageContext + Asynchronous coroutine to fetch the MessageInstance - :param sid: The sid - :returns: twilio.rest.chat.v1.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v1.service.channel.message.MessageContext + :returns: The fetched MessageInstance """ - return MessageContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MessageInstance( self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + def update( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: """ - Provide a friendly representation + Update the MessageInstance - :returns: Machine friendly representation - :rtype: str + :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 '' + data = values.of( + { + "Body": body, + "Attributes": attributes, + } + ) + headers = values.of({}) -class MessagePage(Page): - """ """ + 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"], + ) - def __init__(self, version, response, solution): + async def update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: """ - Initialize the MessagePage + Asynchronous coroutine to update the MessageInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :param channel_sid: The channel_sid + :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: twilio.rest.chat.v1.service.channel.message.MessagePage - :rtype: twilio.rest.chat.v1.service.channel.message.MessagePage + :returns: The updated MessageInstance """ - super(MessagePage, self).__init__(version, response) - # Path Solution - self._solution = solution + 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 + ) - def get_instance(self, payload): + 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: """ - Build an instance of MessageInstance + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v1.service.channel.message.MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance +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'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class MessageContext(InstanceContext): - """ """ +class MessageList(ListResource): - def __init__(self, version, service_sid, channel_sid, sid): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ - Initialize the MessageContext + Initialize the MessageList - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param channel_sid: The channel_sid - :param sid: The sid + :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`. - :returns: twilio.rest.chat.v1.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v1.service.channel.message.MessageContext """ - super(MessageContext, self).__init__(version) + 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) + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Messages".format( + **self._solution + ) - def fetch(self): + def create( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: """ - Fetch a MessageInstance + Create the MessageInstance - :returns: Fetched MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.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 """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def delete(self): + async def create_async( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: """ - Deletes the MessageInstance + Asynchronously create the MessageInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :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. - def update(self, body=values.unset, attributes=values.unset): + :returns: The created MessageInstance """ - Update the MessageInstance - :param unicode body: The body - :param unicode attributes: The attributes + data = values.of( + { + "Body": body, + "From": from_, + "Attributes": attributes, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: Updated MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance - """ - data = values.of({'Body': body, 'Attributes': attributes, }) + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def __repr__(self): + def stream( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: """ - Provide a friendly representation + 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. - :returns: Machine friendly representation - :rtype: str + :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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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"]) -class MessageInstance(InstanceResource): - """ """ + 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. - class OrderType(object): - ASC = "asc" - DESC = "desc" + :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) - def __init__(self, version, payload, service_sid, channel_sid, sid=None): - """ - Initialize the MessageInstance - - :returns: twilio.rest.chat.v1.service.channel.message.MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance - """ - super(MessageInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'attributes': payload['attributes'], - 'service_sid': payload['service_sid'], - 'to': payload['to'], - 'channel_sid': payload['channel_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'was_edited': payload['was_edited'], - 'from_': payload['from'], - 'body': payload['body'], - 'index': deserialize.integer(payload['index']), - 'url': payload['url'], - } + :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"]) - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], - } + return self._version.stream_async(page, limits["limit"]) - @property - def _proxy(self): + def list( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: MessageContext for this MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageContext - """ - 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'], + :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, ) - return self._context + ) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + async def list_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: """ - return self._properties['sid'] + 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. - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + :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, + ) + ] - @property - def attributes(self): + 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: """ - :returns: The attributes - :rtype: unicode - """ - return self._properties['attributes'] + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] + :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 - @property - def to(self): - """ - :returns: The to - :rtype: unicode + :returns: Page of MessageInstance """ - return self._properties['to'] + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def channel_sid(self): - """ - :returns: The channel_sid - :rtype: unicode - """ - return self._properties['channel_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + headers["Accept"] = "application/json" - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) - @property - def was_edited(self): - """ - :returns: The was_edited - :rtype: bool + 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: """ - return self._properties['was_edited'] + Asynchronously retrieve a single page of MessageInstance records from the API. + Request is executed immediately - @property - def from_(self): - """ - :returns: The from - :rtype: unicode - """ - return self._properties['from_'] + :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 - @property - def body(self): - """ - :returns: The body - :rtype: unicode + :returns: Page of MessageInstance """ - return self._properties['body'] + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def index(self): - """ - :returns: The index - :rtype: unicode - """ - return self._properties['index'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def url(self): - """ - :returns: The url - :rtype: unicode + 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: """ - return self._properties['url'] + Retrieve a specific page of MessageInstance records from the API. + Request is executed immediately - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance """ - Fetch a MessageInstance + response = self._version.domain.twilio.request("GET", target_url) + return MessagePage(self._version, response, self._solution) - :returns: Fetched MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance + async def get_page_async(self, target_url: str) -> MessagePage: """ - return self._proxy.fetch() + 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 - def delete(self): + :returns: Page of MessageInstance """ - Deletes the MessageInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagePage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def get(self, sid: str) -> MessageContext: """ - return self._proxy.delete() + Constructs a MessageContext - def update(self, body=values.unset, attributes=values.unset): + :param sid: The Twilio-provided string that uniquely identifies the Message resource to update. """ - Update the MessageInstance + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - :param unicode body: The body - :param unicode attributes: The attributes + def __call__(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext - :returns: Updated MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance + :param sid: The Twilio-provided string that uniquely identifies the Message resource to update. """ - return self._proxy.update(body=body, attributes=attributes, ) + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/chat/v1/service/role.py b/twilio/rest/chat/v1/service/role.py index 1ec84b0b1f..d81cbd55ac 100644 --- a/twilio/rest/chat/v1/service/role.py +++ b/twilio/rest/chat/v1/service/role.py @@ -1,460 +1,645 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 RoleList(ListResource): - """ """ +class RoleInstance(InstanceResource): - def __init__(self, version, service_sid): - """ - Initialize the RoleList + class RoleType(object): + CHANNEL = "channel" + DEPLOYMENT = "deployment" - :param Version version: Version that contains the resource - :param service_sid: The service_sid + """ + :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 - :returns: twilio.rest.chat.v1.service.role.RoleList - :rtype: twilio.rest.chat.v1.service.role.RoleList + @property + def _proxy(self) -> "RoleContext": """ - super(RoleList, self).__init__(version) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Roles'.format(**self._solution) + :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 create(self, friendly_name, type, permission): + def delete(self) -> bool: """ - Create a new RoleInstance + Deletes the RoleInstance - :param unicode friendly_name: The friendly_name - :param RoleInstance.RoleType type: The type - :param unicode permission: The permission - :returns: Newly created RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Type': type, - 'Permission': serialize.map(permission, lambda e: e), - }) + return self._proxy.delete() - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance - return RoleInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return await self._proxy.delete_async() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.role.RoleInstance] + def fetch(self) -> "RoleInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the RoleInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched RoleInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the RoleInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.role.RoleInstance] + :returns: The fetched RoleInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def update(self, permission: List[str]) -> "RoleInstance": """ - Retrieve a single page of RoleInstance records from the API. - Request is executed immediately + Update the RoleInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :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: Page of RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RolePage + :returns: The updated RoleInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + return self._proxy.update( + permission=permission, ) - return RolePage(self._version, response, self._solution) - - def get_page(self, target_url): + async def update_async(self, permission: List[str]) -> "RoleInstance": """ - Retrieve a specific page of RoleInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the RoleInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RolePage + :returns: The updated RoleInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + permission=permission, ) - return RolePage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a RoleContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - :param sid: The sid +class RoleContext(InstanceContext): - :returns: twilio.rest.chat.v1.service.role.RoleContext - :rtype: twilio.rest.chat.v1.service.role.RoleContext + def __init__(self, version: Version, service_sid: str, sid: str): """ - return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Initialize the RoleContext - def __call__(self, sid): + :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. """ - Constructs a RoleContext + super().__init__(version) - :param sid: The sid + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Roles/{sid}".format(**self._solution) - :returns: twilio.rest.chat.v1.service.role.RoleContext - :rtype: twilio.rest.chat.v1.service.role.RoleContext + def delete(self) -> bool: """ - return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Deletes the RoleInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class RolePage(Page): - """ """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, response, solution): + async def delete_async(self) -> bool: """ - Initialize the RolePage + Asynchronous coroutine that deletes the RoleInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :returns: twilio.rest.chat.v1.service.role.RolePage - :rtype: twilio.rest.chat.v1.service.role.RolePage + :returns: True if delete succeeds, False otherwise """ - super(RolePage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: """ - Build an instance of RoleInstance + Fetch the RoleInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v1.service.role.RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance + :returns: The fetched RoleInstance """ - return RoleInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def __repr__(self): - """ - Provide a friendly representation + headers = values.of({}) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Accept"] = "application/json" + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) -class RoleContext(InstanceContext): - """ """ + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - def __init__(self, version, service_sid, sid): + async def fetch_async(self) -> RoleInstance: """ - Initialize the RoleContext + Asynchronous coroutine to fetch the RoleInstance - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: The sid - :returns: twilio.rest.chat.v1.service.role.RoleContext - :rtype: twilio.rest.chat.v1.service.role.RoleContext + :returns: The fetched RoleInstance """ - super(RoleContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Roles/{sid}'.format(**self._solution) + 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 fetch(self): + def update(self, permission: List[str]) -> RoleInstance: """ - Fetch a 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: Fetched RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance + :returns: The updated RoleInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def update_async(self, permission: List[str]) -> RoleInstance: """ - Deletes the RoleInstance + Asynchronous coroutine to update the RoleInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :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. - def update(self, permission): + :returns: The updated RoleInstance """ - Update the RoleInstance - :param unicode permission: The permission + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) - :returns: Updated RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance - """ - data = values.of({'Permission': serialize.map(permission, lambda e: e), }) + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class RoleInstance(InstanceResource): - """ """ +class RolePage(Page): - class RoleType(object): - CHANNEL = "channel" - DEPLOYMENT = "deployment" + def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: + """ + Build an instance of RoleInstance - def __init__(self, version, payload, service_sid, sid=None): + :param payload: Payload response from the API """ - Initialize the RoleInstance + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - :returns: twilio.rest.chat.v1.service.role.RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance + def __repr__(self) -> str: """ - super(RoleInstance, self).__init__(version) + Provide a friendly representation - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'friendly_name': payload['friendly_name'], - 'type': payload['type'], - 'permissions': payload['permissions'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - } + :returns: Machine friendly representation + """ + return "" - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context +class RoleList(ListResource): - :returns: RoleContext for this RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleContext + def __init__(self, version: Version, service_sid: str): """ - if self._context is None: - self._context = RoleContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + 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. - @property - def sid(self): """ - :returns: The sid - :rtype: unicode + 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: """ - return self._properties['sid'] + Create the RoleInstance - @property - def account_sid(self): + :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 """ - :returns: The account_sid - :rtype: unicode + + 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: """ - return self._properties['account_sid'] + Asynchronously create the RoleInstance - @property - def service_sid(self): + :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 """ - :returns: The service_sid - :rtype: unicode + + 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]: """ - return self._properties['service_sid'] + 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. - @property - def friendly_name(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The friendly_name - :rtype: unicode + 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]: """ - return self._properties['friendly_name'] + 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. - @property - def type(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The type - :rtype: RoleInstance.RoleType + 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]: """ - return self._properties['type'] + Lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def permissions(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The permissions - :rtype: unicode + 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]: """ - return self._properties['permissions'] + 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. - @property - def date_created(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The date_created - :rtype: datetime + 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: """ - return self._properties['date_created'] + Retrieve a single page of RoleInstance records from the API. + Request is executed immediately - @property - def date_updated(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The date_updated - :rtype: datetime + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page of RoleInstance records from the API. + Request is executed immediately - @property - def url(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The url - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of RoleInstance """ - Fetch a RoleInstance + response = self._version.domain.twilio.request("GET", target_url) + return RolePage(self._version, response, self._solution) - :returns: Fetched RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance + async def get_page_async(self, target_url: str) -> RolePage: """ - return self._proxy.fetch() + 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 - def delete(self): + :returns: Page of RoleInstance """ - Deletes the RoleInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return RolePage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def get(self, sid: str) -> RoleContext: """ - return self._proxy.delete() + Constructs a RoleContext - def update(self, permission): + :param sid: The Twilio-provided string that uniquely identifies the Role resource to update. """ - Update the RoleInstance + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - :param unicode permission: The permission + def __call__(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext - :returns: Updated RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance + :param sid: The Twilio-provided string that uniquely identifies the Role resource to update. """ - return self._proxy.update(permission, ) + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/chat/v1/service/user/__init__.py b/twilio/rest/chat/v1/service/user/__init__.py index cc9af0b148..c6b900957c 100644 --- a/twilio/rest/chat/v1/service/user/__init__.py +++ b/twilio/rest/chat/v1/service/user/__init__.py @@ -1,539 +1,723 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 UserList(ListResource): - """ """ - - def __init__(self, version, service_sid): - """ - Initialize the UserList +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") - :param Version version: Version that contains the resource - :param service_sid: The service_sid + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[UserContext] = None - :returns: twilio.rest.chat.v1.service.user.UserList - :rtype: twilio.rest.chat.v1.service.user.UserList + @property + def _proxy(self) -> "UserContext": """ - super(UserList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Users'.format(**self._solution) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def create(self, identity, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset): + :returns: UserContext for this UserInstance """ - Create a new UserInstance - - :param unicode identity: The identity - :param unicode role_sid: The role_sid - :param unicode attributes: The attributes - :param unicode friendly_name: The friendly_name + if self._context is None: + self._context = UserContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: Newly created UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance + def delete(self) -> bool: """ - data = values.of({ - 'Identity': identity, - 'RoleSid': role_sid, - 'Attributes': attributes, - 'FriendlyName': friendly_name, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + Deletes the UserInstance - return UserInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.user.UserInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the UserInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the UserInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.user.UserInstance] + :returns: The fetched UserInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_async(self) -> "UserInstance": """ - Retrieve a single page of UserInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the UserInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserPage + :returns: The fetched UserInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return UserPage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def get_page(self, target_url): + def update( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": """ - Retrieve a specific page of UserInstance records from the API. - Request is executed immediately + Update the UserInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserPage + :returns: The updated UserInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, ) - return UserPage(self._version, response, self._solution) - - def get(self, 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": """ - Constructs a UserContext + Asynchronous coroutine to update the UserInstance - :param sid: The sid + :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: twilio.rest.chat.v1.service.user.UserContext - :rtype: twilio.rest.chat.v1.service.user.UserContext + :returns: The updated UserInstance """ - return UserContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_async( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) - def __call__(self, sid): + @property + def user_channels(self) -> UserChannelList: """ - Constructs a UserContext - - :param sid: The sid - - :returns: twilio.rest.chat.v1.service.user.UserContext - :rtype: twilio.rest.chat.v1.service.user.UserContext + Access the user_channels """ - return UserContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.user_channels - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class UserPage(Page): - """ """ +class UserContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the UserPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid + Initialize the UserContext - :returns: twilio.rest.chat.v1.service.user.UserPage - :rtype: twilio.rest.chat.v1.service.user.UserPage + :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(UserPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Users/{sid}".format(**self._solution) - def get_instance(self, payload): + self._user_channels: Optional[UserChannelList] = None + + def delete(self) -> bool: """ - Build an instance of UserInstance + Deletes the UserInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v1.service.user.UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance + :returns: True if delete succeeds, False otherwise """ - return UserInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the UserInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class UserContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, service_sid, sid): + def fetch(self) -> UserInstance: """ - Initialize the UserContext + Fetch the UserInstance - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: The sid - :returns: twilio.rest.chat.v1.service.user.UserContext - :rtype: twilio.rest.chat.v1.service.user.UserContext + :returns: The fetched UserInstance """ - super(UserContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Users/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - # Dependents - self._user_channels = None + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - def fetch(self): + async def fetch_async(self) -> UserInstance: """ - Fetch a UserInstance + Asynchronous coroutine to fetch the UserInstance - :returns: Fetched UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance + + :returns: The fetched UserInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + def update( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: """ - Deletes the UserInstance + Update the UserInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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._version.delete('delete', self._uri) - def update(self, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset): + 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: """ - Update the UserInstance + Asynchronous coroutine to update the UserInstance - :param unicode role_sid: The role_sid - :param unicode attributes: The attributes - :param unicode friendly_name: The friendly_name + :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: Updated UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance + :returns: The updated UserInstance """ - data = values.of({'RoleSid': role_sid, 'Attributes': attributes, 'FriendlyName': friendly_name, }) - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) @property - def user_channels(self): + def user_channels(self) -> UserChannelList: """ Access the user_channels - - :returns: twilio.rest.chat.v1.service.user.user_channel.UserChannelList - :rtype: twilio.rest.chat.v1.service.user.user_channel.UserChannelList """ if self._user_channels is None: self._user_channels = UserChannelList( self._version, - service_sid=self._solution['service_sid'], - user_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) return self._user_channels - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class UserInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the UserInstance - - :returns: twilio.rest.chat.v1.service.user.UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance - """ - super(UserInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'attributes': payload['attributes'], - 'friendly_name': payload['friendly_name'], - 'role_sid': payload['role_sid'], - 'identity': payload['identity'], - 'is_online': payload['is_online'], - 'is_notifiable': payload['is_notifiable'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'joined_channels_count': deserialize.integer(payload['joined_channels_count']), - 'links': payload['links'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } +class UserPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> UserInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of UserInstance - :returns: UserContext for this UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = UserContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def sid(self): + def __repr__(self) -> str: """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] - @property - def attributes(self): - """ - :returns: The attributes - :rtype: unicode - """ - return self._properties['attributes'] +class UserList(ListResource): - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode + def __init__(self, version: Version, service_sid: str): """ - return self._properties['friendly_name'] + Initialize the UserList - @property - def role_sid(self): - """ - :returns: The role_sid - :rtype: unicode - """ - return self._properties['role_sid'] + :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. - @property - def identity(self): """ - :returns: The identity - :rtype: unicode + 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: """ - return self._properties['identity'] + Create the UserInstance - @property - def is_online(self): + :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 """ - :returns: The is_online - :rtype: bool + + 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: """ - return self._properties['is_online'] + Asynchronously create the UserInstance - @property - def is_notifiable(self): + :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 """ - :returns: The is_notifiable - :rtype: bool + + 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]: """ - return self._properties['is_notifiable'] + 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. - @property - def date_created(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The date_created - :rtype: datetime + 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]: """ - return self._properties['date_created'] + 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. - @property - def date_updated(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The date_updated - :rtype: datetime + 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]: """ - return self._properties['date_updated'] + Lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def joined_channels_count(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The joined_channels_count - :rtype: unicode + 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]: """ - return self._properties['joined_channels_count'] + 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. - @property - def links(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The links - :rtype: unicode + 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: """ - return self._properties['links'] + Retrieve a single page of UserInstance records from the API. + Request is executed immediately - @property - def url(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The url - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of UserInstance """ - Fetch a 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) - :returns: Fetched UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance + def get_page(self, target_url: str) -> UserPage: """ - return self._proxy.fetch() + Retrieve a specific page of UserInstance records from the API. + Request is executed immediately - def delete(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance """ - Deletes the UserInstance + response = self._version.domain.twilio.request("GET", target_url) + return UserPage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def get_page_async(self, target_url: str) -> UserPage: """ - return self._proxy.delete() + 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 - def update(self, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset): + :returns: Page of UserInstance """ - Update the UserInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserPage(self._version, response, self._solution) - :param unicode role_sid: The role_sid - :param unicode attributes: The attributes - :param unicode friendly_name: The friendly_name + def get(self, sid: str) -> UserContext: + """ + Constructs a UserContext - :returns: Updated UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance + :param sid: The Twilio-provided string that uniquely identifies the User resource to update. """ - return self._proxy.update(role_sid=role_sid, attributes=attributes, friendly_name=friendly_name, ) + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - @property - def user_channels(self): + def __call__(self, sid: str) -> UserContext: """ - Access the user_channels + Constructs a UserContext - :returns: twilio.rest.chat.v1.service.user.user_channel.UserChannelList - :rtype: twilio.rest.chat.v1.service.user.user_channel.UserChannelList + :param sid: The Twilio-provided string that uniquely identifies the User resource to update. """ - return self._proxy.user_channels + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/chat/v1/service/user/user_channel.py b/twilio/rest/chat/v1/service/user/user_channel.py index 32990f44e6..b7f35aa9ef 100644 --- a/twilio/rest/chat/v1/service/user/user_channel.py +++ b/twilio/rest/chat/v1/service/user/user_channel.py @@ -1,277 +1,322 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 UserChannelList(ListResource): - """ """ - - def __init__(self, version, service_sid, user_sid): - """ - Initialize the UserChannelList +class UserChannelInstance(InstanceResource): - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param user_sid: The sid + class ChannelStatus(object): + JOINED = "joined" + INVITED = "invited" + NOT_PARTICIPATING = "not_participating" - :returns: twilio.rest.chat.v1.service.user.user_channel.UserChannelList - :rtype: twilio.rest.chat.v1.service.user.user_channel.UserChannelList - """ - super(UserChannelList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'service_sid': service_sid, 'user_sid': user_sid, } - self._uri = '/Services/{service_sid}/Users/{user_sid}/Channels'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + } - def stream(self, limit=None, page_size=None): + def __repr__(self) -> str: """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Provide a friendly representation - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.user.user_channel.UserChannelInstance] + :returns: Machine friendly representation """ - limits = self._version.read_limits(limit, page_size) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) +class UserChannelPage(Page): - def list(self, limit=None, page_size=None): + def get_instance(self, payload: Dict[str, Any]) -> 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + Build an instance of UserChannelInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.user.user_channel.UserChannelInstance] + :param payload: Payload response from the API """ - return list(self.stream(limit=limit, page_size=page_size, )) + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + ) - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def __repr__(self) -> str: """ - Retrieve a single page of UserChannelInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + Provide a friendly representation - :returns: Page of UserChannelInstance - :rtype: twilio.rest.chat.v1.service.user.user_channel.UserChannelPage + :returns: Machine friendly representation """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return "" - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - return UserChannelPage(self._version, response, self._solution) +class UserChannelList(ListResource): - def get_page(self, target_url): + def __init__(self, version: Version, service_sid: str, user_sid: str): """ - Retrieve a specific page of UserChannelInstance records from the API. - Request is executed immediately + Initialize the UserChannelList - :param str target_url: API-generated URL for the requested results page + :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. - :returns: Page of UserChannelInstance - :rtype: twilio.rest.chat.v1.service.user.user_channel.UserChannelPage """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + super().__init__(version) - return UserChannelPage(self._version, response, self._solution) + # 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 __repr__(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserChannelInstance]: """ - Provide a friendly representation + 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. - :returns: Machine friendly representation - :rtype: str - """ - return '' + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.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"]) -class UserChannelPage(Page): - """ """ + return self._version.stream(page, limits["limit"]) - def __init__(self, version, response, solution): + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserChannelInstance]: """ - Initialize the UserChannelPage + 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 Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :param user_sid: The 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: twilio.rest.chat.v1.service.user.user_channel.UserChannelPage - :rtype: twilio.rest.chat.v1.service.user.user_channel.UserChannelPage + :returns: Generator that will yield up to limit results """ - super(UserChannelPage, self).__init__(version, response) + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - # Path Solution - self._solution = solution + return self._version.stream_async(page, limits["limit"]) - def get_instance(self, payload): + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: """ - Build an instance of 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 dict payload: Payload response from the API + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - :returns: twilio.rest.chat.v1.service.user.user_channel.UserChannelInstance - :rtype: twilio.rest.chat.v1.service.user.user_channel.UserChannelInstance + :returns: list that will contain up to limit results """ - return UserChannelInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], + return list( + self.stream( + limit=limit, + page_size=page_size, + ) ) - def __repr__(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: """ - Provide a friendly representation + 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. - :returns: Machine friendly representation - :rtype: str + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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: """ - return '' + 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 -class UserChannelInstance(InstanceResource): - """ """ + :returns: Page of UserChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - class ChannelStatus(object): - JOINED = "joined" - INVITED = "invited" - NOT_PARTICIPATING = "not_participating" + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def __init__(self, version, payload, service_sid, user_sid): - """ - Initialize the UserChannelInstance + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserChannelPage(self._version, response, self._solution) - :returns: twilio.rest.chat.v1.service.user.user_channel.UserChannelInstance - :rtype: twilio.rest.chat.v1.service.user.user_channel.UserChannelInstance + 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: """ - super(UserChannelInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'channel_sid': payload['channel_sid'], - 'member_sid': payload['member_sid'], - 'status': payload['status'], - 'last_consumed_message_index': deserialize.integer(payload['last_consumed_message_index']), - 'unread_messages_count': deserialize.integer(payload['unread_messages_count']), - 'links': payload['links'], - } + Asynchronously retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'user_sid': user_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 - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + :returns: Page of UserChannelInstance """ - return self._properties['account_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def channel_sid(self): - """ - :returns: The channel_sid - :rtype: unicode - """ - return self._properties['channel_sid'] + headers["Accept"] = "application/json" - @property - def member_sid(self): - """ - :returns: The member_sid - :rtype: unicode - """ - return self._properties['member_sid'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserChannelPage(self._version, response, self._solution) - @property - def status(self): + def get_page(self, target_url: str) -> UserChannelPage: """ - :returns: The status - :rtype: UserChannelInstance.ChannelStatus - """ - return self._properties['status'] + Retrieve a specific page of UserChannelInstance records from the API. + Request is executed immediately - @property - def last_consumed_message_index(self): - """ - :returns: The last_consumed_message_index - :rtype: unicode - """ - return self._properties['last_consumed_message_index'] + :param target_url: API-generated URL for the requested results page - @property - def unread_messages_count(self): - """ - :returns: The unread_messages_count - :rtype: unicode + :returns: Page of UserChannelInstance """ - return self._properties['unread_messages_count'] + response = self._version.domain.twilio.request("GET", target_url) + return UserChannelPage(self._version, response, self._solution) - @property - def links(self): + async def get_page_async(self, target_url: str) -> UserChannelPage: """ - :returns: The links - :rtype: unicode + 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 """ - return self._properties['links'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserChannelPage(self._version, response, self._solution) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/chat/v2/__init__.py b/twilio/rest/chat/v2/__init__.py index 099c5d8e94..e949532d56 100644 --- a/twilio/rest/chat/v2/__init__.py +++ b/twilio/rest/chat/v2/__init__.py @@ -1,53 +1,51 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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): + def __init__(self, domain: Domain): """ Initialize the V2 version of Chat - :returns: V2 version of Chat - :rtype: twilio.rest.chat.v2.V2.V2 + :param domain: The Twilio.chat domain """ - super(V2, self).__init__(domain) - self.version = 'v2' - self._credentials = None - self._services = None + super().__init__(domain, "v2") + self._credentials: Optional[CredentialList] = None + self._services: Optional[ServiceList] = None @property - def credentials(self): - """ - :rtype: twilio.rest.chat.v2.credential.CredentialList - """ + def credentials(self) -> CredentialList: if self._credentials is None: self._credentials = CredentialList(self) return self._credentials @property - def services(self): - """ - :rtype: twilio.rest.chat.v2.service.ServiceList - """ + def services(self) -> ServiceList: if self._services is None: self._services = ServiceList(self) return self._services - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/chat/v2/credential.py b/twilio/rest/chat/v2/credential.py index df2e268f99..5479abeca0 100644 --- a/twilio/rest/chat/v2/credential.py +++ b/twilio/rest/chat/v2/credential.py @@ -1,472 +1,711 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 CredentialList(ListResource): - """ """ - - def __init__(self, version): - """ - Initialize the CredentialList +class CredentialInstance(InstanceResource): - :param Version version: Version that contains the resource + class PushService(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" - :returns: twilio.rest.chat.v2.credential.CredentialList - :rtype: twilio.rest.chat.v2.credential.CredentialList - """ - super(CredentialList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {} - self._uri = '/Credentials'.format(**self._solution) + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CredentialContext] = None - def stream(self, limit=None, page_size=None): + @property + def _proxy(self) -> "CredentialContext": """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.credential.CredentialInstance] + :returns: CredentialContext for this CredentialInstance """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def list(self, limit=None, page_size=None): + def delete(self) -> bool: """ - Lists CredentialInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the CredentialInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.credential.CredentialInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.delete() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def delete_async(self) -> bool: """ - Retrieve a single page of CredentialInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the CredentialInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialPage + :returns: True if delete succeeds, False otherwise """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + return await self._proxy.delete_async() - return CredentialPage(self._version, response, self._solution) - - def get_page(self, target_url): + def fetch(self) -> "CredentialInstance": """ - Retrieve a specific page of CredentialInstance records from the API. - Request is executed immediately + Fetch the CredentialInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialPage + :returns: The fetched CredentialInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return CredentialPage(self._version, response, self._solution) + return self._proxy.fetch() - def create(self, type, friendly_name=values.unset, certificate=values.unset, - private_key=values.unset, sandbox=values.unset, api_key=values.unset, - secret=values.unset): + async def fetch_async(self) -> "CredentialInstance": """ - Create a new CredentialInstance + Asynchronous coroutine to fetch the CredentialInstance - :param CredentialInstance.PushService type: The type - :param unicode friendly_name: The friendly_name - :param unicode certificate: The certificate - :param unicode private_key: The private_key - :param bool sandbox: The sandbox - :param unicode api_key: The api_key - :param unicode secret: The secret - :returns: Newly created CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance + :returns: The fetched CredentialInstance """ - data = values.of({ - 'Type': type, - 'FriendlyName': friendly_name, - 'Certificate': certificate, - 'PrivateKey': private_key, - 'Sandbox': sandbox, - 'ApiKey': api_key, - 'Secret': secret, - }) + return await self._proxy.fetch_async() - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return CredentialInstance(self._version, payload, ) - - def get(self, 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": """ - Constructs a CredentialContext + Update the CredentialInstance - :param sid: The sid + :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: twilio.rest.chat.v2.credential.CredentialContext - :rtype: twilio.rest.chat.v2.credential.CredentialContext + :returns: The updated CredentialInstance """ - return CredentialContext(self._version, sid=sid, ) + return self._proxy.update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - def __call__(self, 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": """ - Constructs a CredentialContext + Asynchronous coroutine to update the CredentialInstance - :param sid: The sid + :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: twilio.rest.chat.v2.credential.CredentialContext - :rtype: twilio.rest.chat.v2.credential.CredentialContext + :returns: The updated CredentialInstance """ - return CredentialContext(self._version, sid=sid, ) + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class CredentialPage(Page): - """ """ +class CredentialContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the CredentialPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the CredentialContext - :returns: twilio.rest.chat.v2.credential.CredentialPage - :rtype: twilio.rest.chat.v2.credential.CredentialPage + :param version: Version that contains the resource + :param sid: The SID of the Credential resource to update. """ - super(CredentialPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) - def get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of CredentialInstance + Deletes the CredentialInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v2.credential.CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance + :returns: True if delete succeeds, False otherwise """ - return CredentialInstance(self._version, payload, ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the CredentialInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class CredentialContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, sid): + def fetch(self) -> CredentialInstance: """ - Initialize the CredentialContext + Fetch the CredentialInstance - :param Version version: Version that contains the resource - :param sid: The sid - :returns: twilio.rest.chat.v2.credential.CredentialContext - :rtype: twilio.rest.chat.v2.credential.CredentialContext + :returns: The fetched CredentialInstance """ - super(CredentialContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Credentials/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialInstance: """ - Fetch a CredentialInstance + Asynchronous coroutine to fetch the CredentialInstance - :returns: Fetched CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance + + :returns: The fetched CredentialInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], ) + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def update(self, friendly_name=values.unset, certificate=values.unset, - private_key=values.unset, sandbox=values.unset, api_key=values.unset, - secret=values.unset): + 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 unicode friendly_name: The friendly_name - :param unicode certificate: The certificate - :param unicode private_key: The private_key - :param bool sandbox: The sandbox - :param unicode api_key: The api_key - :param unicode secret: The secret - - :returns: Updated CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Certificate': certificate, - 'PrivateKey': private_key, - 'Sandbox': sandbox, - 'ApiKey': api_key, - 'Secret': secret, - }) + :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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) - return CredentialInstance(self._version, payload, sid=self._solution['sid'], ) + 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({}) - def delete(self): - """ - Deletes the CredentialInstance + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + headers["Accept"] = "application/json" - def __repr__(self): + 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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class CredentialInstance(InstanceResource): - """ """ +class CredentialPage(Page): - class PushService(object): - GCM = "gcm" - APN = "apn" - FCM = "fcm" + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: + """ + Build an instance of CredentialInstance - def __init__(self, version, payload, sid=None): + :param payload: Payload response from the API """ - Initialize the CredentialInstance + return CredentialInstance(self._version, payload) - :returns: twilio.rest.chat.v2.credential.CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance + def __repr__(self) -> str: """ - super(CredentialInstance, self).__init__(version) + Provide a friendly representation - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'friendly_name': payload['friendly_name'], - 'type': payload['type'], - 'sandbox': payload['sandbox'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - } + :returns: Machine friendly representation + """ + return "" - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context +class CredentialList(ListResource): - :returns: CredentialContext for this CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialContext + def __init__(self, version: Version): """ - if self._context is None: - self._context = CredentialContext(self._version, sid=self._solution['sid'], ) - return self._context + Initialize the CredentialList + + :param version: Version that contains the resource - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode """ - return self._properties['sid'] + super().__init__(version) - @property - def account_sid(self): + 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: """ - :returns: The account_sid - :rtype: unicode + 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 """ - return self._properties['account_sid'] - @property - def friendly_name(self): + 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]: """ - :returns: The friendly_name - :rtype: unicode + 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 """ - return self._properties['friendly_name'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def type(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialInstance]: """ - :returns: The type - :rtype: CredentialInstance.PushService + 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 """ - return self._properties['type'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def sandbox(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: """ - :returns: The sandbox - :rtype: unicode + 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 self._properties['sandbox'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def date_created(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: """ - :returns: The date_created - :rtype: datetime + 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: """ - return self._properties['date_created'] + Retrieve a single page of CredentialInstance records from the API. + Request is executed immediately - @property - def date_updated(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The date_updated - :rtype: datetime + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page of CredentialInstance records from the API. + Request is executed immediately - @property - def url(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The url - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['url'] + Retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance """ - Fetch a CredentialInstance + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) - :returns: Fetched CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance + async def get_page_async(self, target_url: str) -> CredentialPage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately - def update(self, friendly_name=values.unset, certificate=values.unset, - private_key=values.unset, sandbox=values.unset, api_key=values.unset, - secret=values.unset): + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance """ - Update the CredentialInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response) - :param unicode friendly_name: The friendly_name - :param unicode certificate: The certificate - :param unicode private_key: The private_key - :param bool sandbox: The sandbox - :param unicode api_key: The api_key - :param unicode secret: The secret + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext - :returns: Updated CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance + :param sid: The SID of the Credential resource to update. """ - return self._proxy.update( - friendly_name=friendly_name, - certificate=certificate, - private_key=private_key, - sandbox=sandbox, - api_key=api_key, - secret=secret, - ) + return CredentialContext(self._version, sid=sid) - def delete(self): + def __call__(self, sid: str) -> CredentialContext: """ - Deletes the CredentialInstance + Constructs a CredentialContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The SID of the Credential resource to update. """ - return self._proxy.delete() + return CredentialContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/chat/v2/service/__init__.py b/twilio/rest/chat/v2/service/__init__.py index 80b9947d99..90a6c6cdba 100644 --- a/twilio/rest/chat/v2/service/__init__.py +++ b/twilio/rest/chat/v2/service/__init__.py @@ -1,17 +1,24 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 @@ -19,817 +26,1103 @@ from twilio.rest.chat.v2.service.user import UserList -class ServiceList(ListResource): - """ """ - - def __init__(self, version): - """ - Initialize the ServiceList +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") - :param Version version: Version that contains the resource + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None - :returns: twilio.rest.chat.v2.service.ServiceList - :rtype: twilio.rest.chat.v2.service.ServiceList + @property + def _proxy(self) -> "ServiceContext": """ - super(ServiceList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Services'.format(**self._solution) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def create(self, friendly_name): + :returns: ServiceContext for this ServiceInstance """ - Create a new ServiceInstance - - :param unicode friendly_name: The friendly_name + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: Newly created ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance + def delete(self) -> bool: """ - data = values.of({'FriendlyName': friendly_name, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + Deletes the ServiceInstance - return ServiceInstance(self._version, payload, ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.ServiceInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the ServiceInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the ServiceInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.ServiceInstance] + :returns: The fetched ServiceInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + 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": """ - Retrieve a single page of ServiceInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + Update the ServiceInstance - :returns: Page of ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServicePage + :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 """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + 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, ) - return ServicePage(self._version, response, self._solution) + 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, + ) - def get_page(self, target_url): + @property + def bindings(self) -> BindingList: """ - Retrieve a specific page of ServiceInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServicePage + Access the bindings """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ServicePage(self._version, response, self._solution) + return self._proxy.bindings - def get(self, sid): + @property + def channels(self) -> ChannelList: """ - Constructs a ServiceContext - - :param sid: The sid - - :returns: twilio.rest.chat.v2.service.ServiceContext - :rtype: twilio.rest.chat.v2.service.ServiceContext + Access the channels """ - return ServiceContext(self._version, sid=sid, ) + return self._proxy.channels - def __call__(self, sid): + @property + def roles(self) -> RoleList: """ - Constructs a ServiceContext - - :param sid: The sid + Access the roles + """ + return self._proxy.roles - :returns: twilio.rest.chat.v2.service.ServiceContext - :rtype: twilio.rest.chat.v2.service.ServiceContext + @property + def users(self) -> UserList: """ - return ServiceContext(self._version, sid=sid, ) + Access the users + """ + return self._proxy.users - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ServicePage(Page): - """ """ +class ServiceContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the ServicePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the ServiceContext - :returns: twilio.rest.chat.v2.service.ServicePage - :rtype: twilio.rest.chat.v2.service.ServicePage + :param version: Version that contains the resource + :param sid: The SID of the Service resource to update. """ - super(ServicePage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of ServiceInstance + Deletes the ServiceInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v2.service.ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance + :returns: True if delete succeeds, False otherwise """ - return ServiceInstance(self._version, payload, ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the ServiceInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class ServiceContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, sid): + def fetch(self) -> ServiceInstance: """ - Initialize the ServiceContext + Fetch the ServiceInstance - :param Version version: Version that contains the resource - :param sid: The sid - :returns: twilio.rest.chat.v2.service.ServiceContext - :rtype: twilio.rest.chat.v2.service.ServiceContext + :returns: The fetched ServiceInstance """ - super(ServiceContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Services/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - # Dependents - self._channels = None - self._roles = None - self._users = None - self._bindings = None + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def fetch(self): + async def fetch_async(self) -> ServiceInstance: """ - Fetch a ServiceInstance + Asynchronous coroutine to fetch the ServiceInstance + - :returns: Fetched ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance + :returns: The fetched ServiceInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) + headers = values.of({}) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" - def delete(self): - """ - Deletes the ServiceInstance + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def update(self, friendly_name=values.unset, - default_service_role_sid=values.unset, - default_channel_role_sid=values.unset, - default_channel_creator_role_sid=values.unset, - read_status_enabled=values.unset, reachability_enabled=values.unset, - typing_indicator_timeout=values.unset, - consumption_report_interval=values.unset, - notifications_new_message_enabled=values.unset, - notifications_new_message_template=values.unset, - notifications_new_message_sound=values.unset, - notifications_new_message_badge_count_enabled=values.unset, - notifications_added_to_channel_enabled=values.unset, - notifications_added_to_channel_template=values.unset, - notifications_added_to_channel_sound=values.unset, - notifications_removed_from_channel_enabled=values.unset, - notifications_removed_from_channel_template=values.unset, - notifications_removed_from_channel_sound=values.unset, - notifications_invited_to_channel_enabled=values.unset, - notifications_invited_to_channel_template=values.unset, - notifications_invited_to_channel_sound=values.unset, - pre_webhook_url=values.unset, post_webhook_url=values.unset, - webhook_method=values.unset, webhook_filters=values.unset, - limits_channel_members=values.unset, - limits_user_channels=values.unset, - media_compatibility_message=values.unset, - pre_webhook_retry_count=values.unset, - post_webhook_retry_count=values.unset, - notifications_log_enabled=values.unset): + 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 unicode friendly_name: The friendly_name - :param unicode default_service_role_sid: The default_service_role_sid - :param unicode default_channel_role_sid: The default_channel_role_sid - :param unicode default_channel_creator_role_sid: The default_channel_creator_role_sid - :param bool read_status_enabled: The read_status_enabled - :param bool reachability_enabled: The reachability_enabled - :param unicode typing_indicator_timeout: The typing_indicator_timeout - :param unicode consumption_report_interval: The consumption_report_interval - :param bool notifications_new_message_enabled: The notifications.new_message.enabled - :param unicode notifications_new_message_template: The notifications.new_message.template - :param unicode notifications_new_message_sound: The notifications.new_message.sound - :param bool notifications_new_message_badge_count_enabled: The notifications.new_message.badge_count_enabled - :param bool notifications_added_to_channel_enabled: The notifications.added_to_channel.enabled - :param unicode notifications_added_to_channel_template: The notifications.added_to_channel.template - :param unicode notifications_added_to_channel_sound: The notifications.added_to_channel.sound - :param bool notifications_removed_from_channel_enabled: The notifications.removed_from_channel.enabled - :param unicode notifications_removed_from_channel_template: The notifications.removed_from_channel.template - :param unicode notifications_removed_from_channel_sound: The notifications.removed_from_channel.sound - :param bool notifications_invited_to_channel_enabled: The notifications.invited_to_channel.enabled - :param unicode notifications_invited_to_channel_template: The notifications.invited_to_channel.template - :param unicode notifications_invited_to_channel_sound: The notifications.invited_to_channel.sound - :param unicode pre_webhook_url: The pre_webhook_url - :param unicode post_webhook_url: The post_webhook_url - :param unicode webhook_method: The webhook_method - :param unicode webhook_filters: The webhook_filters - :param unicode limits_channel_members: The limits.channel_members - :param unicode limits_user_channels: The limits.user_channels - :param unicode media_compatibility_message: The media.compatibility_message - :param unicode pre_webhook_retry_count: The pre_webhook_retry_count - :param unicode post_webhook_retry_count: The post_webhook_retry_count - :param bool notifications_log_enabled: The notifications.log_enabled - - :returns: Updated ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'DefaultServiceRoleSid': default_service_role_sid, - 'DefaultChannelRoleSid': default_channel_role_sid, - 'DefaultChannelCreatorRoleSid': default_channel_creator_role_sid, - 'ReadStatusEnabled': read_status_enabled, - 'ReachabilityEnabled': reachability_enabled, - 'TypingIndicatorTimeout': typing_indicator_timeout, - 'ConsumptionReportInterval': consumption_report_interval, - 'Notifications.NewMessage.Enabled': notifications_new_message_enabled, - 'Notifications.NewMessage.Template': notifications_new_message_template, - 'Notifications.NewMessage.Sound': notifications_new_message_sound, - 'Notifications.NewMessage.BadgeCountEnabled': notifications_new_message_badge_count_enabled, - 'Notifications.AddedToChannel.Enabled': notifications_added_to_channel_enabled, - 'Notifications.AddedToChannel.Template': notifications_added_to_channel_template, - 'Notifications.AddedToChannel.Sound': notifications_added_to_channel_sound, - 'Notifications.RemovedFromChannel.Enabled': notifications_removed_from_channel_enabled, - 'Notifications.RemovedFromChannel.Template': notifications_removed_from_channel_template, - 'Notifications.RemovedFromChannel.Sound': notifications_removed_from_channel_sound, - 'Notifications.InvitedToChannel.Enabled': 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': notifications_log_enabled, - }) + :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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + 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 channels(self): + def bindings(self) -> BindingList: """ - Access the channels + Access the bindings + """ + if self._bindings is None: + self._bindings = BindingList( + self._version, + self._solution["sid"], + ) + return self._bindings - :returns: twilio.rest.chat.v2.service.channel.ChannelList - :rtype: twilio.rest.chat.v2.service.channel.ChannelList + @property + def channels(self) -> ChannelList: + """ + Access the channels """ if self._channels is None: - self._channels = ChannelList(self._version, service_sid=self._solution['sid'], ) + self._channels = ChannelList( + self._version, + self._solution["sid"], + ) return self._channels @property - def roles(self): + def roles(self) -> RoleList: """ Access the roles - - :returns: twilio.rest.chat.v2.service.role.RoleList - :rtype: twilio.rest.chat.v2.service.role.RoleList """ if self._roles is None: - self._roles = RoleList(self._version, service_sid=self._solution['sid'], ) + self._roles = RoleList( + self._version, + self._solution["sid"], + ) return self._roles @property - def users(self): + def users(self) -> UserList: """ Access the users - - :returns: twilio.rest.chat.v2.service.user.UserList - :rtype: twilio.rest.chat.v2.service.user.UserList """ if self._users is None: - self._users = UserList(self._version, service_sid=self._solution['sid'], ) + self._users = UserList( + self._version, + self._solution["sid"], + ) return self._users - @property - def bindings(self): - """ - Access the bindings - - :returns: twilio.rest.chat.v2.service.binding.BindingList - :rtype: twilio.rest.chat.v2.service.binding.BindingList - """ - if self._bindings is None: - self._bindings = BindingList(self._version, service_sid=self._solution['sid'], ) - return self._bindings - - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ServiceInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, sid=None): - """ - Initialize the ServiceInstance - - :returns: twilio.rest.chat.v2.service.ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance - """ - super(ServiceInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'friendly_name': payload['friendly_name'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'default_service_role_sid': payload['default_service_role_sid'], - 'default_channel_role_sid': payload['default_channel_role_sid'], - 'default_channel_creator_role_sid': payload['default_channel_creator_role_sid'], - 'read_status_enabled': payload['read_status_enabled'], - 'reachability_enabled': payload['reachability_enabled'], - 'typing_indicator_timeout': deserialize.integer(payload['typing_indicator_timeout']), - 'consumption_report_interval': deserialize.integer(payload['consumption_report_interval']), - 'limits': payload['limits'], - 'pre_webhook_url': payload['pre_webhook_url'], - 'post_webhook_url': payload['post_webhook_url'], - 'webhook_method': payload['webhook_method'], - 'webhook_filters': payload['webhook_filters'], - 'pre_webhook_retry_count': deserialize.integer(payload['pre_webhook_retry_count']), - 'post_webhook_retry_count': deserialize.integer(payload['post_webhook_retry_count']), - 'notifications': payload['notifications'], - 'media': payload['media'], - 'url': payload['url'], - 'links': payload['links'], - } - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } +class ServicePage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of ServiceInstance - :returns: ServiceContext for this ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = ServiceContext(self._version, sid=self._solution['sid'], ) - return self._context + return ServiceInstance(self._version, payload) - @property - def sid(self): + def __repr__(self) -> str: """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] +class ServiceList(ListResource): - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime + def __init__(self, version: Version): """ - return self._properties['date_updated'] + Initialize the ServiceList - @property - def default_service_role_sid(self): - """ - :returns: The default_service_role_sid - :rtype: unicode - """ - return self._properties['default_service_role_sid'] + :param version: Version that contains the resource - @property - def default_channel_role_sid(self): - """ - :returns: The default_channel_role_sid - :rtype: unicode """ - return self._properties['default_channel_role_sid'] + super().__init__(version) - @property - def default_channel_creator_role_sid(self): - """ - :returns: The default_channel_creator_role_sid - :rtype: unicode - """ - return self._properties['default_channel_creator_role_sid'] + self._uri = "/Services" - @property - def read_status_enabled(self): + def create(self, friendly_name: str) -> ServiceInstance: """ - :returns: The read_status_enabled - :rtype: bool - """ - return self._properties['read_status_enabled'] + Create the ServiceInstance - @property - def reachability_enabled(self): - """ - :returns: The reachability_enabled - :rtype: bool - """ - return self._properties['reachability_enabled'] + :param friendly_name: A descriptive string that you create to describe the new resource. - @property - def typing_indicator_timeout(self): + :returns: The created ServiceInstance """ - :returns: The typing_indicator_timeout - :rtype: unicode - """ - return self._properties['typing_indicator_timeout'] - @property - def consumption_report_interval(self): - """ - :returns: The consumption_report_interval - :rtype: unicode - """ - return self._properties['consumption_report_interval'] + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def limits(self): - """ - :returns: The limits - :rtype: dict - """ - return self._properties['limits'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def pre_webhook_url(self): - """ - :returns: The pre_webhook_url - :rtype: unicode - """ - return self._properties['pre_webhook_url'] + headers["Accept"] = "application/json" - @property - def post_webhook_url(self): - """ - :returns: The post_webhook_url - :rtype: unicode - """ - return self._properties['post_webhook_url'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def webhook_method(self): - """ - :returns: The webhook_method - :rtype: unicode - """ - return self._properties['webhook_method'] + return ServiceInstance(self._version, payload) - @property - def webhook_filters(self): - """ - :returns: The webhook_filters - :rtype: unicode + async def create_async(self, friendly_name: str) -> ServiceInstance: """ - return self._properties['webhook_filters'] + Asynchronously create the ServiceInstance - @property - def pre_webhook_retry_count(self): - """ - :returns: The pre_webhook_retry_count - :rtype: unicode - """ - return self._properties['pre_webhook_retry_count'] + :param friendly_name: A descriptive string that you create to describe the new resource. - @property - def post_webhook_retry_count(self): - """ - :returns: The post_webhook_retry_count - :rtype: unicode + :returns: The created ServiceInstance """ - return self._properties['post_webhook_retry_count'] - @property - def notifications(self): - """ - :returns: The notifications - :rtype: dict - """ - return self._properties['notifications'] + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def media(self): - """ - :returns: The media - :rtype: dict + 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]: """ - return self._properties['media'] + 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. - @property - def url(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The url - :rtype: unicode + 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]: """ - return self._properties['url'] + 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. - @property - def links(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The links - :rtype: unicode + 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]: """ - return self._properties['links'] + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - def fetch(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - Fetch a ServiceInstance + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - :returns: Fetched ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: """ - return self._proxy.fetch() + 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. - def delete(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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: """ - Deletes the ServiceInstance + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param page_token: PageToken provided by the API + :param page_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 """ - return self._proxy.delete() + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" - def update(self, friendly_name=values.unset, - default_service_role_sid=values.unset, - default_channel_role_sid=values.unset, - default_channel_creator_role_sid=values.unset, - read_status_enabled=values.unset, reachability_enabled=values.unset, - typing_indicator_timeout=values.unset, - consumption_report_interval=values.unset, - notifications_new_message_enabled=values.unset, - notifications_new_message_template=values.unset, - notifications_new_message_sound=values.unset, - notifications_new_message_badge_count_enabled=values.unset, - notifications_added_to_channel_enabled=values.unset, - notifications_added_to_channel_template=values.unset, - notifications_added_to_channel_sound=values.unset, - notifications_removed_from_channel_enabled=values.unset, - notifications_removed_from_channel_template=values.unset, - notifications_removed_from_channel_sound=values.unset, - notifications_invited_to_channel_enabled=values.unset, - notifications_invited_to_channel_template=values.unset, - notifications_invited_to_channel_sound=values.unset, - pre_webhook_url=values.unset, post_webhook_url=values.unset, - webhook_method=values.unset, webhook_filters=values.unset, - limits_channel_members=values.unset, - limits_user_channels=values.unset, - media_compatibility_message=values.unset, - pre_webhook_retry_count=values.unset, - post_webhook_retry_count=values.unset, - notifications_log_enabled=values.unset): + 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: """ - Update the ServiceInstance + 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 - :param unicode friendly_name: The friendly_name - :param unicode default_service_role_sid: The default_service_role_sid - :param unicode default_channel_role_sid: The default_channel_role_sid - :param unicode default_channel_creator_role_sid: The default_channel_creator_role_sid - :param bool read_status_enabled: The read_status_enabled - :param bool reachability_enabled: The reachability_enabled - :param unicode typing_indicator_timeout: The typing_indicator_timeout - :param unicode consumption_report_interval: The consumption_report_interval - :param bool notifications_new_message_enabled: The notifications.new_message.enabled - :param unicode notifications_new_message_template: The notifications.new_message.template - :param unicode notifications_new_message_sound: The notifications.new_message.sound - :param bool notifications_new_message_badge_count_enabled: The notifications.new_message.badge_count_enabled - :param bool notifications_added_to_channel_enabled: The notifications.added_to_channel.enabled - :param unicode notifications_added_to_channel_template: The notifications.added_to_channel.template - :param unicode notifications_added_to_channel_sound: The notifications.added_to_channel.sound - :param bool notifications_removed_from_channel_enabled: The notifications.removed_from_channel.enabled - :param unicode notifications_removed_from_channel_template: The notifications.removed_from_channel.template - :param unicode notifications_removed_from_channel_sound: The notifications.removed_from_channel.sound - :param bool notifications_invited_to_channel_enabled: The notifications.invited_to_channel.enabled - :param unicode notifications_invited_to_channel_template: The notifications.invited_to_channel.template - :param unicode notifications_invited_to_channel_sound: The notifications.invited_to_channel.sound - :param unicode pre_webhook_url: The pre_webhook_url - :param unicode post_webhook_url: The post_webhook_url - :param unicode webhook_method: The webhook_method - :param unicode webhook_filters: The webhook_filters - :param unicode limits_channel_members: The limits.channel_members - :param unicode limits_user_channels: The limits.user_channels - :param unicode media_compatibility_message: The media.compatibility_message - :param unicode pre_webhook_retry_count: The pre_webhook_retry_count - :param unicode post_webhook_retry_count: The post_webhook_retry_count - :param bool notifications_log_enabled: The notifications.log_enabled - - :returns: Updated ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance + :returns: Page of 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, + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } ) - @property - def channels(self): + headers = values.of({"Content-Type": "application/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: """ - Access the channels + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately - :returns: twilio.rest.chat.v2.service.channel.ChannelList - :rtype: twilio.rest.chat.v2.service.channel.ChannelList + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance """ - return self._proxy.channels + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) - @property - def roles(self): + async def get_page_async(self, target_url: str) -> ServicePage: """ - Access the roles + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately - :returns: twilio.rest.chat.v2.service.role.RoleList - :rtype: twilio.rest.chat.v2.service.role.RoleList + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance """ - return self._proxy.roles + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) - @property - def users(self): + def get(self, sid: str) -> ServiceContext: """ - Access the users + Constructs a ServiceContext - :returns: twilio.rest.chat.v2.service.user.UserList - :rtype: twilio.rest.chat.v2.service.user.UserList + :param sid: The SID of the Service resource to update. """ - return self._proxy.users + return ServiceContext(self._version, sid=sid) - @property - def bindings(self): + def __call__(self, sid: str) -> ServiceContext: """ - Access the bindings + Constructs a ServiceContext - :returns: twilio.rest.chat.v2.service.binding.BindingList - :rtype: twilio.rest.chat.v2.service.binding.BindingList + :param sid: The SID of the Service resource to update. """ - return self._proxy.bindings + return ServiceContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/chat/v2/service/binding.py b/twilio/rest/chat/v2/service/binding.py index 720f394c86..125f4b9368 100644 --- a/twilio/rest/chat/v2/service/binding.py +++ b/twilio/rest/chat/v2/service/binding.py @@ -1,448 +1,536 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 BindingList(ListResource): - """ """ - - def __init__(self, version, service_sid): - """ - Initialize the BindingList +class BindingInstance(InstanceResource): - :param Version version: Version that contains the resource - :param service_sid: The service_sid + class BindingType(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" - :returns: twilio.rest.chat.v2.service.binding.BindingList - :rtype: twilio.rest.chat.v2.service.binding.BindingList - """ - super(BindingList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Bindings'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[BindingContext] = None - def stream(self, binding_type=values.unset, identity=values.unset, limit=None, - page_size=None): + @property + def _proxy(self) -> "BindingContext": """ - 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. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param BindingInstance.BindingType binding_type: The binding_type - :param unicode identity: The identity - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.binding.BindingInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the BindingInstance - page = self.page(binding_type=binding_type, identity=identity, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, binding_type=values.unset, identity=values.unset, limit=None, - page_size=None): + async def delete_async(self) -> bool: """ - Lists BindingInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the BindingInstance - :param BindingInstance.BindingType binding_type: The binding_type - :param unicode identity: The identity - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.binding.BindingInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream( - binding_type=binding_type, - identity=identity, - limit=limit, - page_size=page_size, - )) + return await self._proxy.delete_async() - def page(self, binding_type=values.unset, identity=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "BindingInstance": """ - Retrieve a single page of BindingInstance records from the API. - Request is executed immediately + Fetch the BindingInstance - :param BindingInstance.BindingType binding_type: The binding_type - :param unicode identity: The identity - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of BindingInstance - :rtype: twilio.rest.chat.v2.service.binding.BindingPage + :returns: The fetched BindingInstance """ - params = 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, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return BindingPage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "BindingInstance": """ - Retrieve a specific page of BindingInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the BindingInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of BindingInstance - :rtype: twilio.rest.chat.v2.service.binding.BindingPage + :returns: The fetched BindingInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return await self._proxy.fetch_async() - return BindingPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a BindingContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - :param sid: The sid +class BindingContext(InstanceContext): - :returns: twilio.rest.chat.v2.service.binding.BindingContext - :rtype: twilio.rest.chat.v2.service.binding.BindingContext + def __init__(self, version: Version, service_sid: str, sid: str): """ - return BindingContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Initialize the BindingContext - def __call__(self, sid): + :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. """ - Constructs a BindingContext + super().__init__(version) - :param sid: The sid + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Bindings/{sid}".format(**self._solution) - :returns: twilio.rest.chat.v2.service.binding.BindingContext - :rtype: twilio.rest.chat.v2.service.binding.BindingContext + def delete(self) -> bool: """ - return BindingContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Deletes the BindingInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class BindingPage(Page): - """ """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, response, solution): + async def delete_async(self) -> bool: """ - Initialize the BindingPage + Asynchronous coroutine that deletes the BindingInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :returns: twilio.rest.chat.v2.service.binding.BindingPage - :rtype: twilio.rest.chat.v2.service.binding.BindingPage + :returns: True if delete succeeds, False otherwise """ - super(BindingPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): - """ - Build an instance of BindingInstance - - :param dict payload: Payload response from the API + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v2.service.binding.BindingInstance - :rtype: twilio.rest.chat.v2.service.binding.BindingInstance + def fetch(self) -> BindingInstance: """ - return BindingInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Fetch the BindingInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: The fetched BindingInstance """ - return '' + headers = values.of({}) -class BindingContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, service_sid, sid): - """ - Initialize the BindingContext + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: The sid + return BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.chat.v2.service.binding.BindingContext - :rtype: twilio.rest.chat.v2.service.binding.BindingContext + async def fetch_async(self) -> BindingInstance: """ - super(BindingContext, self).__init__(version) + Asynchronous coroutine to fetch the BindingInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Bindings/{sid}'.format(**self._solution) - def fetch(self): + :returns: The fetched BindingInstance """ - Fetch a BindingInstance - :returns: Fetched BindingInstance - :rtype: twilio.rest.chat.v2.service.binding.BindingInstance - """ - params = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + def __repr__(self) -> str: """ - Deletes the BindingInstance + Provide a friendly representation - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: Machine friendly representation """ - return self._version.delete('delete', self._uri) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - def __repr__(self): + +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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" -class BindingInstance(InstanceResource): - """ """ - - class BindingType(object): - GCM = "gcm" - APN = "apn" - FCM = "fcm" +class BindingList(ListResource): - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the BindingInstance - - :returns: twilio.rest.chat.v2.service.binding.BindingInstance - :rtype: twilio.rest.chat.v2.service.binding.BindingInstance - """ - super(BindingInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'endpoint': payload['endpoint'], - 'identity': payload['identity'], - 'credential_sid': payload['credential_sid'], - 'binding_type': payload['binding_type'], - 'message_types': payload['message_types'], - 'url': payload['url'], - 'links': payload['links'], - } + def __init__(self, version: Version, service_sid: str): + """ + Initialize the BindingList - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + :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. - @property - def _proxy(self): """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + super().__init__(version) - :returns: BindingContext for this BindingInstance - :rtype: twilio.rest.chat.v2.service.binding.BindingContext - """ - if self._context is None: - self._context = BindingContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Bindings".format(**self._solution) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + 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]: """ - return self._properties['sid'] + 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. - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + :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) - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['service_sid'] + limits = self._version.read_limits(limit, page_size) + page = self.page( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + return self._version.stream(page, limits["limit"]) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime + 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]: """ - return self._properties['date_updated'] + 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. - @property - def endpoint(self): - """ - :returns: The endpoint - :rtype: unicode - """ - return self._properties['endpoint'] + :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) - @property - def identity(self): - """ - :returns: The identity - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['identity'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) - @property - def credential_sid(self): + 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]: """ - :returns: The credential_sid - :rtype: unicode + 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]: """ - return self._properties['credential_sid'] + 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. - @property - def binding_type(self): + :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: """ - :returns: The binding_type - :rtype: BindingInstance.BindingType + 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 """ - return self._properties['binding_type'] + 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, + } + ) - @property - def message_types(self): + headers = values.of({"Content-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: """ - :returns: The message_types - :rtype: unicode + 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 """ - return self._properties['message_types'] + 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, + } + ) - @property - def url(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + response = self._version.domain.twilio.request("GET", target_url) + return BindingPage(self._version, response, self._solution) - @property - def links(self): + async def get_page_async(self, target_url: str) -> BindingPage: """ - :returns: The links - :rtype: unicode + 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 """ - return self._properties['links'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return BindingPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> BindingContext: """ - Fetch a BindingInstance + Constructs a BindingContext - :returns: Fetched BindingInstance - :rtype: twilio.rest.chat.v2.service.binding.BindingInstance + :param sid: The SID of the Binding resource to fetch. """ - return self._proxy.fetch() + return BindingContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def delete(self): + def __call__(self, sid: str) -> BindingContext: """ - Deletes the BindingInstance + Constructs a BindingContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The SID of the Binding resource to fetch. """ - return self._proxy.delete() + return BindingContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/chat/v2/service/channel/__init__.py b/twilio/rest/chat/v2/service/channel/__init__.py index e770ca1780..36d08a3896 100644 --- a/twilio/rest/chat/v2/service/channel/__init__.py +++ b/twilio/rest/chat/v2/service/channel/__init__.py @@ -1,638 +1,962 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 ChannelList(ListResource): - """ """ - - def __init__(self, version, service_sid): - """ - Initialize the ChannelList - - :param Version version: Version that contains the resource - :param service_sid: The service_sid - - :returns: twilio.rest.chat.v2.service.channel.ChannelList - :rtype: twilio.rest.chat.v2.service.channel.ChannelList - """ - super(ChannelList, self).__init__(version) +class ChannelInstance(InstanceResource): - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Channels'.format(**self._solution) - - def create(self, friendly_name=values.unset, unique_name=values.unset, - attributes=values.unset, type=values.unset, - date_created=values.unset, date_updated=values.unset, - created_by=values.unset): - """ - Create a new ChannelInstance - - :param unicode friendly_name: The friendly_name - :param unicode unique_name: The unique_name - :param unicode attributes: The attributes - :param ChannelInstance.ChannelType type: The type - :param datetime date_created: The date_created - :param datetime date_updated: The date_updated - :param unicode created_by: The created_by - - :returns: Newly created ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.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, - }) + class ChannelType(object): + PUBLIC = "public" + PRIVATE = "private" - payload = self._version.create( - 'POST', - self._uri, - data=data, + 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") - return ChannelInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ChannelContext] = None - def stream(self, type=values.unset, limit=None, page_size=None): + @property + def _proxy(self) -> "ChannelContext": """ - 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. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param ChannelInstance.ChannelType type: The type - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.ChannelInstance] + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the ChannelInstance - page = self.page(type=type, page_size=limits['page_size'], ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - def list(self, type=values.unset, limit=None, page_size=None): + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Lists ChannelInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the ChannelInstance - :param ChannelInstance.ChannelType type: The type - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.ChannelInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(type=type, limit=limit, page_size=page_size, )) + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - def page(self, type=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch(self) -> "ChannelInstance": """ - Retrieve a single page of ChannelInstance records from the API. - Request is executed immediately + Fetch the ChannelInstance - :param ChannelInstance.ChannelType type: The type - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelPage + :returns: The fetched ChannelInstance """ - params = values.of({ - 'Type': serialize.map(type, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + async def fetch_async(self) -> "ChannelInstance": + """ + Asynchronous coroutine to fetch the ChannelInstance - return ChannelPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched ChannelInstance """ - Retrieve a specific page of ChannelInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_async() - :param str target_url: API-generated URL for the requested results page - - :returns: Page of ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelPage + 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": """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Update the ChannelInstance - return ChannelPage(self._version, response, self._solution) + :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`. - def get(self, sid): + :returns: The updated ChannelInstance """ - Constructs a ChannelContext + 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, + ) - :param sid: The 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 + """ + 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, + ) - :returns: twilio.rest.chat.v2.service.channel.ChannelContext - :rtype: twilio.rest.chat.v2.service.channel.ChannelContext + @property + def invites(self) -> InviteList: """ - return ChannelContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Access the invites + """ + return self._proxy.invites - def __call__(self, sid): + @property + def members(self) -> MemberList: """ - Constructs a ChannelContext + Access the members + """ + return self._proxy.members - :param sid: The sid + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages - :returns: twilio.rest.chat.v2.service.channel.ChannelContext - :rtype: twilio.rest.chat.v2.service.channel.ChannelContext + @property + def webhooks(self) -> WebhookList: """ - return ChannelContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Access the webhooks + """ + return self._proxy.webhooks - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ChannelPage(Page): - """ """ +class ChannelContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the ChannelPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid + Initialize the ChannelContext - :returns: twilio.rest.chat.v2.service.channel.ChannelPage - :rtype: twilio.rest.chat.v2.service.channel.ChannelPage + :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(ChannelPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Build an instance of ChannelInstance + Deletes the ChannelInstance - :param dict payload: Payload response from the API + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: twilio.rest.chat.v2.service.channel.ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance + :returns: True if delete succeeds, False otherwise """ - return ChannelInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + 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) - def __repr__(self): + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the ChannelInstance - :returns: Machine friendly representation - :rtype: str + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + headers = values.of({}) -class ChannelContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, service_sid, sid): + def fetch(self) -> ChannelInstance: """ - Initialize the ChannelContext + Fetch the ChannelInstance - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: The sid - :returns: twilio.rest.chat.v2.service.channel.ChannelContext - :rtype: twilio.rest.chat.v2.service.channel.ChannelContext + :returns: The fetched ChannelInstance """ - super(ChannelContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Channels/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - # Dependents - self._members = None - self._messages = None - self._invites = None + 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"], + ) - def fetch(self): + async def fetch_async(self) -> ChannelInstance: """ - Fetch a ChannelInstance + Asynchronous coroutine to fetch the ChannelInstance - :returns: Fetched ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance + + :returns: The fetched ChannelInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + 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: """ - Deletes the ChannelInstance + Update the ChannelInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :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({}) - def update(self, friendly_name=values.unset, unique_name=values.unset, - attributes=values.unset, date_created=values.unset, - date_updated=values.unset, created_by=values.unset): - """ - Update the ChannelInstance + 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" - :param unicode friendly_name: The friendly_name - :param unicode unique_name: The unique_name - :param unicode attributes: The attributes - :param datetime date_created: The date_created - :param datetime date_updated: The date_updated - :param unicode created_by: The created_by - - :returns: Updated ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.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["Accept"] = "application/json" payload = self._version.update( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) return ChannelInstance( self._version, payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + 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 members(self): + def invites(self) -> InviteList: """ - Access the members + Access the invites + """ + if self._invites is None: + self._invites = InviteList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._invites - :returns: twilio.rest.chat.v2.service.channel.member.MemberList - :rtype: twilio.rest.chat.v2.service.channel.member.MemberList + @property + def members(self) -> MemberList: + """ + Access the members """ if self._members is None: self._members = MemberList( self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) return self._members @property - def messages(self): + def messages(self) -> MessageList: """ Access the messages - - :returns: twilio.rest.chat.v2.service.channel.message.MessageList - :rtype: twilio.rest.chat.v2.service.channel.message.MessageList """ if self._messages is None: self._messages = MessageList( self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) return self._messages @property - def invites(self): + def webhooks(self) -> WebhookList: """ - Access the invites - - :returns: twilio.rest.chat.v2.service.channel.invite.InviteList - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteList + Access the webhooks """ - if self._invites is None: - self._invites = InviteList( + if self._webhooks is None: + self._webhooks = WebhookList( self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) - return self._invites + return self._webhooks - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class ChannelInstance(InstanceResource): - """ """ - - class ChannelType(object): - PUBLIC = "public" - PRIVATE = "private" + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the ChannelInstance - - :returns: twilio.rest.chat.v2.service.channel.ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance - """ - super(ChannelInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'friendly_name': payload['friendly_name'], - 'unique_name': payload['unique_name'], - 'attributes': payload['attributes'], - 'type': payload['type'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'created_by': payload['created_by'], - 'members_count': deserialize.integer(payload['members_count']), - 'messages_count': deserialize.integer(payload['messages_count']), - 'url': payload['url'], - 'links': payload['links'], - } - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } +class ChannelPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of ChannelInstance - :returns: ChannelContext for this ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = ChannelContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] +class ChannelList(ListResource): - @property - def unique_name(self): + def __init__(self, version: Version, service_sid: str): """ - :returns: The unique_name - :rtype: unicode - """ - return self._properties['unique_name'] + Initialize the ChannelList - @property - def attributes(self): - """ - :returns: The attributes - :rtype: unicode - """ - return self._properties['attributes'] + :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. - @property - def type(self): - """ - :returns: The type - :rtype: ChannelInstance.ChannelType """ - return self._properties['type'] + super().__init__(version) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + # 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", + } + ) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def created_by(self): - """ - :returns: The created_by - :rtype: unicode - """ - return self._properties['created_by'] + headers["Accept"] = "application/json" - @property - def members_count(self): - """ - :returns: The members_count - :rtype: unicode - """ - return self._properties['members_count'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def messages_count(self): + 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]: """ - :returns: The messages_count - :rtype: unicode + 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 """ - return self._properties['messages_count'] + limits = self._version.read_limits(limit, page_size) + page = self.page(type=type, page_size=limits["page_size"]) - @property - def url(self): + 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]: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(type=type, page_size=limits["page_size"]) - @property - def links(self): + 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]: """ - :returns: The links - :rtype: unicode + 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]: """ - return self._properties['links'] + 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 fetch(self): + 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: """ - Fetch a ChannelInstance + 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: Fetched ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance + :returns: Page of ChannelInstance """ - return self._proxy.fetch() + 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" - def delete(self): + 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: """ - Deletes the ChannelInstance + Asynchronously retrieve a single page of ChannelInstance records from the API. + Request is executed immediately - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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 """ - return self._proxy.delete() + 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"}) - def update(self, friendly_name=values.unset, unique_name=values.unset, - attributes=values.unset, date_created=values.unset, - date_updated=values.unset, created_by=values.unset): + 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: """ - Update the ChannelInstance + Retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately - :param unicode friendly_name: The friendly_name - :param unicode unique_name: The unique_name - :param unicode attributes: The attributes - :param datetime date_created: The date_created - :param datetime date_updated: The date_updated - :param unicode created_by: The created_by + :param target_url: API-generated URL for the requested results page - :returns: Updated ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance + :returns: Page of ChannelInstance """ - return self._proxy.update( - friendly_name=friendly_name, - unique_name=unique_name, - attributes=attributes, - date_created=date_created, - date_updated=date_updated, - created_by=created_by, - ) + response = self._version.domain.twilio.request("GET", target_url) + return ChannelPage(self._version, response, self._solution) - @property - def members(self): + async def get_page_async(self, target_url: str) -> ChannelPage: """ - Access the members + Asynchronously retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately - :returns: twilio.rest.chat.v2.service.channel.member.MemberList - :rtype: twilio.rest.chat.v2.service.channel.member.MemberList + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance """ - return self._proxy.members + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelPage(self._version, response, self._solution) - @property - def messages(self): + def get(self, sid: str) -> ChannelContext: """ - Access the messages + Constructs a ChannelContext - :returns: twilio.rest.chat.v2.service.channel.message.MessageList - :rtype: twilio.rest.chat.v2.service.channel.message.MessageList + :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 self._proxy.messages + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - @property - def invites(self): + def __call__(self, sid: str) -> ChannelContext: """ - Access the invites + Constructs a ChannelContext - :returns: twilio.rest.chat.v2.service.channel.invite.InviteList - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteList + :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 self._proxy.invites + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/chat/v2/service/channel/invite.py b/twilio/rest/chat/v2/service/channel/invite.py index d92770af20..7c7f9f6211 100644 --- a/twilio/rest/chat/v2/service/channel/invite.py +++ b/twilio/rest/chat/v2/service/channel/invite.py @@ -1,462 +1,598 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 InviteList(ListResource): - """ """ +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 - def __init__(self, version, service_sid, channel_sid): + @property + def _proxy(self) -> "InviteContext": """ - Initialize the InviteList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param channel_sid: The channel_sid + :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 - :returns: twilio.rest.chat.v2.service.channel.invite.InviteList - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteList + def delete(self) -> bool: """ - super(InviteList, self).__init__(version) + Deletes the InviteInstance - # 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, role_sid=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create a new InviteInstance - - :param unicode identity: The identity - :param unicode role_sid: The role_sid + return self._proxy.delete() - :returns: Newly created InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteInstance + async def delete_async(self) -> bool: """ - data = values.of({'Identity': identity, 'RoleSid': role_sid, }) + Asynchronous coroutine that deletes the InviteInstance - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - return InviteInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - ) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def stream(self, identity=values.unset, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the InviteInstance - :param unicode identity: The identity - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.invite.InviteInstance] + :returns: The fetched InviteInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(identity=identity, page_size=limits['page_size'], ) + async def fetch_async(self) -> "InviteInstance": + """ + Asynchronous coroutine to fetch the InviteInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, identity=values.unset, limit=None, page_size=None): + :returns: The fetched 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 unicode identity: The identity - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + return await self._proxy.fetch_async() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.invite.InviteInstance] + def __repr__(self) -> str: """ - return list(self.stream(identity=identity, limit=limit, page_size=page_size, )) + Provide a friendly representation - def page(self, identity=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + :returns: Machine friendly representation """ - Retrieve a single page of InviteInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param unicode identity: The identity - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InvitePage +class InviteContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ - params = values.of({ - 'Identity': serialize.map(identity, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Initialize the InviteContext - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + :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) - return InvitePage(self._version, response, self._solution) + # 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 get_page(self, target_url): + def delete(self) -> bool: """ - Retrieve a specific page of InviteInstance records from the API. - Request is executed immediately + Deletes the InviteInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InvitePage + :returns: True if delete succeeds, False otherwise """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return InvitePage(self._version, response, self._solution) + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def get(self, sid): + async def delete_async(self) -> bool: """ - Constructs a InviteContext + Asynchronous coroutine that deletes the InviteInstance - :param sid: The sid - :returns: twilio.rest.chat.v2.service.channel.invite.InviteContext - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteContext + :returns: True if delete succeeds, False otherwise """ - return InviteContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers ) - def __call__(self, sid): + def fetch(self) -> InviteInstance: """ - Constructs a InviteContext + Fetch the InviteInstance - :param sid: The sid - :returns: twilio.rest.chat.v2.service.channel.invite.InviteContext - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteContext + :returns: The fetched InviteInstance """ - return InviteContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InviteInstance( self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + async def fetch_async(self) -> InviteInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the InviteInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched InviteInstance """ - return '' + headers = values.of({}) -class InvitePage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): - """ - Initialize the InvitePage + 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"], + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :param channel_sid: The channel_sid + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.chat.v2.service.channel.invite.InvitePage - :rtype: twilio.rest.chat.v2.service.channel.invite.InvitePage + :returns: Machine friendly representation """ - super(InvitePage, self).__init__(version, response) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Path Solution - self._solution = solution - def get_instance(self, payload): +class InvitePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: """ Build an instance of InviteInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.chat.v2.service.channel.invite.InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.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'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class InviteContext(InstanceContext): - """ """ +class InviteList(ListResource): - def __init__(self, version, service_sid, channel_sid, sid): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ - Initialize the InviteContext + Initialize the InviteList - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param channel_sid: The channel_sid - :param sid: The sid + :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`. - :returns: twilio.rest.chat.v2.service.channel.invite.InviteContext - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteContext """ - super(InviteContext, self).__init__(version) + 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) + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Invites".format( + **self._solution + ) - def fetch(self): + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: """ - Fetch a 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: Fetched InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteInstance + :returns: The created InviteInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def delete(self): + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: """ - Deletes the InviteInstance + Asynchronously create the InviteInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :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. - def __repr__(self): + :returns: The created InviteInstance """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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" -class InviteInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - def __init__(self, version, payload, service_sid, channel_sid, sid=None): + 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]: """ - Initialize the 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: twilio.rest.chat.v2.service.channel.invite.InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteInstance + :returns: Generator that will yield up to limit results """ - super(InviteInstance, self).__init__(version) + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'channel_sid': payload['channel_sid'], - 'service_sid': payload['service_sid'], - 'identity': payload['identity'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'role_sid': payload['role_sid'], - 'created_by': payload['created_by'], - 'url': payload['url'], - } + return self._version.stream(page, limits["limit"]) - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], - } + 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. - @property - def _proxy(self): + :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 """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) - :returns: InviteContext for this InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteContext + 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]: """ - 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'], + 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, ) - return self._context + ) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: """ - return self._properties['sid'] + 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. - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + :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, + ) + ] - @property - def channel_sid(self): - """ - :returns: The channel_sid - :rtype: unicode + 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: """ - return self._properties['channel_sid'] + Retrieve a single page of InviteInstance records from the API. + Request is executed immediately - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] + :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 - @property - def identity(self): - """ - :returns: The identity - :rtype: unicode + :returns: Page of InviteInstance """ - return self._properties['identity'] + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Accept"] = "application/json" - @property - def role_sid(self): + 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: """ - :returns: The role_sid - :rtype: unicode + 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 """ - return self._properties['role_sid'] + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def created_by(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The created_by - :rtype: unicode + 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 """ - return self._properties['created_by'] + response = self._version.domain.twilio.request("GET", target_url) + return InvitePage(self._version, response, self._solution) - @property - def url(self): + async def get_page_async(self, target_url: str) -> InvitePage: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return InvitePage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> InviteContext: """ - Fetch a InviteInstance + Constructs a InviteContext - :returns: Fetched InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteInstance + :param sid: The SID of the Invite resource to fetch. """ - return self._proxy.fetch() + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - def delete(self): + def __call__(self, sid: str) -> InviteContext: """ - Deletes the InviteInstance + Constructs a InviteContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The SID of the Invite resource to fetch. """ - return self._proxy.delete() + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/chat/v2/service/channel/member.py b/twilio/rest/chat/v2/service/channel/member.py index 50f701d633..f07cb21891 100644 --- a/twilio/rest/chat/v2/service/channel/member.py +++ b/twilio/rest/chat/v2/service/channel/member.py @@ -1,547 +1,905 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 MemberList(ListResource): - """ """ +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 - def __init__(self, version, service_sid, channel_sid): + @property + def _proxy(self) -> "MemberContext": """ - Initialize the MemberList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param channel_sid: The channel_sid + :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 - :returns: twilio.rest.chat.v2.service.channel.member.MemberList - :rtype: twilio.rest.chat.v2.service.channel.member.MemberList + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - super(MemberList, self).__init__(version) + Deletes the MemberInstance - # 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, role_sid=values.unset, - last_consumed_message_index=values.unset, - last_consumption_timestamp=values.unset, date_created=values.unset, - date_updated=values.unset): - """ - Create a new MemberInstance - - :param unicode identity: The identity - :param unicode role_sid: The role_sid - :param unicode last_consumed_message_index: The last_consumed_message_index - :param datetime last_consumption_timestamp: The last_consumption_timestamp - :param datetime date_created: The date_created - :param datetime date_updated: The date_updated - - :returns: Newly created MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.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), - }) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - payload = self._version.create( - 'POST', - self._uri, - data=data, + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) - return MemberInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], + 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 stream(self, identity=values.unset, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the MemberInstance - :param unicode identity: The identity - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.member.MemberInstance] + :returns: The fetched MemberInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(identity=identity, page_size=limits['page_size'], ) + async def fetch_async(self) -> "MemberInstance": + """ + Asynchronous coroutine to fetch the MemberInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, identity=values.unset, limit=None, page_size=None): + :returns: The fetched 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. + return await self._proxy.fetch_async() - :param unicode identity: The identity - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + 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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.member.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 list(self.stream(identity=identity, limit=limit, page_size=page_size, )) + 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 page(self, identity=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def __repr__(self) -> str: """ - Retrieve a single page of MemberInstance records from the API. - Request is executed immediately + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param unicode identity: The identity - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberPage +class MemberContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ - params = values.of({ - 'Identity': serialize.map(identity, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Initialize the MemberContext - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + :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) - return MemberPage(self._version, response, self._solution) + # 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 get_page(self, target_url): + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Retrieve a specific page of MemberInstance records from the API. - Request is executed immediately + Deletes the MemberInstance - :param str target_url: API-generated URL for the requested results page + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: Page of MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberPage + :returns: True if delete succeeds, False otherwise """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } ) - return MemberPage(self._version, response, self._solution) + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def get(self, sid): + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Constructs a MemberContext + Asynchronous coroutine that deletes the MemberInstance - :param sid: The sid + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: twilio.rest.chat.v2.service.channel.member.MemberContext - :rtype: twilio.rest.chat.v2.service.channel.member.MemberContext + :returns: True if delete succeeds, False otherwise """ - return MemberContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } ) - def __call__(self, sid): + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MemberInstance: """ - Constructs a MemberContext + Fetch the MemberInstance - :param sid: The sid - :returns: twilio.rest.chat.v2.service.channel.member.MemberContext - :rtype: twilio.rest.chat.v2.service.channel.member.MemberContext + :returns: The fetched MemberInstance """ - return MemberContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MemberInstance( self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + async def fetch_async(self) -> MemberInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the MemberInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched MemberInstance """ - return '' + headers = values.of({}) -class MemberPage(Page): - """ """ + 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 __init__(self, version, response, solution): + 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: """ - Initialize the MemberPage + 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"], + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :param channel_sid: The channel_sid + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.chat.v2.service.channel.member.MemberPage - :rtype: twilio.rest.chat.v2.service.channel.member.MemberPage + :returns: Machine friendly representation """ - super(MemberPage, self).__init__(version, response) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Path Solution - self._solution = solution - def get_instance(self, payload): +class MemberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: """ Build an instance of MemberInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.chat.v2.service.channel.member.MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.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'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class MemberContext(InstanceContext): - """ """ +class MemberList(ListResource): - def __init__(self, version, service_sid, channel_sid, sid): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ - Initialize the MemberContext + Initialize the MemberList - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param channel_sid: The channel_sid - :param sid: The sid + :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`. - :returns: twilio.rest.chat.v2.service.channel.member.MemberContext - :rtype: twilio.rest.chat.v2.service.channel.member.MemberContext """ - super(MemberContext, self).__init__(version) + 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) + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Members".format( + **self._solution + ) - def fetch(self): - """ - Fetch a MemberInstance + 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", + } + ) - :returns: Fetched MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberInstance - """ - params = values.of({}) + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def delete(self): - """ - Deletes the MemberInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def update(self, role_sid=values.unset, - last_consumed_message_index=values.unset, - last_consumption_timestamp=values.unset, date_created=values.unset, - date_updated=values.unset): - """ - Update the MemberInstance + 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", + } + ) - :param unicode role_sid: The role_sid - :param unicode last_consumed_message_index: The last_consumed_message_index - :param datetime last_consumption_timestamp: The last_consumption_timestamp - :param datetime date_created: The date_created - :param datetime date_updated: The date_updated + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: Updated MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.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), - }) + headers["Accept"] = "application/json" - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def __repr__(self): + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MemberInstance]: """ - Provide a friendly representation + 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. - :returns: Machine friendly representation - :rtype: str + :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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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"]) -class MemberInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, service_sid, channel_sid, sid=None): - """ - Initialize the MemberInstance - - :returns: twilio.rest.chat.v2.service.channel.member.MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberInstance - """ - super(MemberInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'channel_sid': payload['channel_sid'], - 'service_sid': payload['service_sid'], - 'identity': payload['identity'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'role_sid': payload['role_sid'], - 'last_consumed_message_index': deserialize.integer(payload['last_consumed_message_index']), - 'last_consumption_timestamp': deserialize.iso8601_datetime(payload['last_consumption_timestamp']), - 'url': payload['url'], - } + 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. - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], - } + :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) - @property - def _proxy(self): + :returns: Generator that will yield up to limit results """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) - :returns: MemberContext for this MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberContext + 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]: """ - 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'], + 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, ) - return self._context + ) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: """ - return self._properties['sid'] + 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. - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + :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, + ) + ] - @property - def channel_sid(self): + 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: """ - :returns: The channel_sid - :rtype: unicode - """ - return self._properties['channel_sid'] + Retrieve a single page of MemberInstance records from the API. + Request is executed immediately - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] + :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 - @property - def identity(self): - """ - :returns: The identity - :rtype: unicode + :returns: Page of MemberInstance """ - return self._properties['identity'] + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Accept"] = "application/json" - @property - def role_sid(self): - """ - :returns: The role_sid - :rtype: unicode - """ - return self._properties['role_sid'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, self._solution) - @property - def last_consumed_message_index(self): - """ - :returns: The last_consumed_message_index - :rtype: unicode + 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: """ - return self._properties['last_consumed_message_index'] + Asynchronously retrieve a single page of MemberInstance records from the API. + Request is executed immediately - @property - def last_consumption_timestamp(self): - """ - :returns: The last_consumption_timestamp - :rtype: datetime - """ - return self._properties['last_consumption_timestamp'] + :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 - @property - def url(self): + :returns: Page of MemberInstance """ - :returns: The url - :rtype: unicode + 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: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of MemberInstance """ - Fetch a MemberInstance + response = self._version.domain.twilio.request("GET", target_url) + return MemberPage(self._version, response, self._solution) - :returns: Fetched MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberInstance + async def get_page_async(self, target_url: str) -> MemberPage: """ - return self._proxy.fetch() + 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 - def delete(self): + :returns: Page of MemberInstance """ - Deletes the MemberInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return MemberPage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def get(self, sid: str) -> MemberContext: """ - return self._proxy.delete() + Constructs a MemberContext - def update(self, role_sid=values.unset, - last_consumed_message_index=values.unset, - last_consumption_timestamp=values.unset, date_created=values.unset, - date_updated=values.unset): + :param sid: The SID of the Member resource to update. This value can be either the Member's `sid` or its `identity` value. """ - Update the MemberInstance + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - :param unicode role_sid: The role_sid - :param unicode last_consumed_message_index: The last_consumed_message_index - :param datetime last_consumption_timestamp: The last_consumption_timestamp - :param datetime date_created: The date_created - :param datetime date_updated: The date_updated + def __call__(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext - :returns: Updated MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberInstance + :param sid: The SID of the Member resource to update. This value can be either the Member's `sid` or its `identity` value. """ - return self._proxy.update( - 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, + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/chat/v2/service/channel/message.py b/twilio/rest/chat/v2/service/channel/message.py index 4e3bf4df1d..d0bf2e5ac7 100644 --- a/twilio/rest/chat/v2/service/channel/message.py +++ b/twilio/rest/chat/v2/service/channel/message.py @@ -1,596 +1,905 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 MessageList(ListResource): - """ """ +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") - def __init__(self, version, service_sid, channel_sid): + 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": """ - Initialize the MessageList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param channel_sid: The channel_sid + :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 - :returns: twilio.rest.chat.v2.service.channel.message.MessageList - :rtype: twilio.rest.chat.v2.service.channel.message.MessageList + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - super(MessageList, self).__init__(version) + Deletes the MessageInstance - # 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, from_=values.unset, attributes=values.unset, - date_created=values.unset, date_updated=values.unset, - last_updated_by=values.unset, body=values.unset, - media_sid=values.unset): - """ - Create a new MessageInstance - - :param unicode from_: The from - :param unicode attributes: The attributes - :param datetime date_created: The date_created - :param datetime date_updated: The date_updated - :param unicode last_updated_by: The last_updated_by - :param unicode body: The body - :param unicode media_sid: The media_sid - - :returns: Newly created MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.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, - }) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - payload = self._version.create( - 'POST', - self._uri, - data=data, + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) - return MessageInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], + 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 stream(self, order=values.unset, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the MessageInstance - :param MessageInstance.OrderType order: The order - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.message.MessageInstance] + :returns: The fetched MessageInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(order=order, page_size=limits['page_size'], ) + async def fetch_async(self) -> "MessageInstance": + """ + Asynchronous coroutine to fetch the MessageInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, order=values.unset, limit=None, page_size=None): + :returns: The fetched 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. + return await self._proxy.fetch_async() - :param MessageInstance.OrderType order: The order - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + 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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.message.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 list(self.stream(order=order, limit=limit, page_size=page_size, )) + 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_, + ) - def page(self, order=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + 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: """ - Retrieve a single page of MessageInstance records from the API. - Request is executed immediately + Provide a friendly representation - :param MessageInstance.OrderType order: The order - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: Page of MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessagePage + +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. """ - params = values.of({ - 'Order': order, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + super().__init__(version) - response = self._version.page( - 'GET', - self._uri, - params=params, + # 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 + ) ) - return MessagePage(self._version, response, self._solution) - - def get_page(self, target_url): + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Retrieve a specific page of MessageInstance records from the API. - Request is executed immediately + Deletes the MessageInstance - :param str target_url: API-generated URL for the requested results page + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: Page of MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessagePage + :returns: True if delete succeeds, False otherwise """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } ) - return MessagePage(self._version, response, self._solution) + headers = values.of({}) - def get(self, sid): + 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: """ - Constructs a MessageContext + Asynchronous coroutine that deletes the MessageInstance - :param sid: The sid + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: twilio.rest.chat.v2.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v2.service.channel.message.MessageContext + :returns: True if delete succeeds, False otherwise """ - return MessageContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + 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 __call__(self, sid): + def fetch(self) -> MessageInstance: """ - Constructs a MessageContext + Fetch the MessageInstance - :param sid: The sid - :returns: twilio.rest.chat.v2.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v2.service.channel.message.MessageContext + :returns: The fetched MessageInstance """ - return MessageContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MessageInstance( self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + async def fetch_async(self) -> MessageInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the MessageInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched MessageInstance """ - return '' + headers = values.of({}) -class MessagePage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): + 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: """ - Initialize the MessagePage + Update the MessageInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :param channel_sid: The channel_sid + :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 - :returns: twilio.rest.chat.v2.service.channel.message.MessagePage - :rtype: twilio.rest.chat.v2.service.channel.message.MessagePage + 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: """ - super(MessagePage, self).__init__(version, response) + Provide a friendly representation - # Path Solution - self._solution = solution + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - def get_instance(self, payload): + +class MessagePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: """ Build an instance of MessageInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.chat.v2.service.channel.message.MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.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'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class MessageContext(InstanceContext): - """ """ +class MessageList(ListResource): - def __init__(self, version, service_sid, channel_sid, sid): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ - Initialize the MessageContext + Initialize the MessageList - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param channel_sid: The channel_sid - :param sid: The sid + :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`. - :returns: twilio.rest.chat.v2.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v2.service.channel.message.MessageContext """ - super(MessageContext, self).__init__(version) + 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) + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Messages".format( + **self._solution + ) - def fetch(self): - """ - Fetch a MessageInstance + 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", + } + ) - :returns: Fetched MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance - """ - params = values.of({}) + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def delete(self): - """ - Deletes the MessageInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def update(self, body=values.unset, attributes=values.unset, - date_created=values.unset, date_updated=values.unset, - last_updated_by=values.unset): - """ - Update the MessageInstance + 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", + } + ) - :param unicode body: The body - :param unicode attributes: The attributes - :param datetime date_created: The date_created - :param datetime date_updated: The date_updated - :param unicode last_updated_by: The last_updated_by + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: Updated MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance - """ - data = values.of({ - 'Body': body, - 'Attributes': attributes, - 'DateCreated': serialize.iso8601_datetime(date_created), - 'DateUpdated': serialize.iso8601_datetime(date_updated), - 'LastUpdatedBy': last_updated_by, - }) + headers["Accept"] = "application/json" - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def __repr__(self): + def stream( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: """ - Provide a friendly representation + 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. - :returns: Machine friendly representation - :rtype: str + :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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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"]) -class MessageInstance(InstanceResource): - """ """ + 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. - class OrderType(object): - ASC = "asc" - DESC = "desc" + :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) - def __init__(self, version, payload, service_sid, channel_sid, sid=None): - """ - Initialize the MessageInstance - - :returns: twilio.rest.chat.v2.service.channel.message.MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance - """ - super(MessageInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'attributes': payload['attributes'], - 'service_sid': payload['service_sid'], - 'to': payload['to'], - 'channel_sid': payload['channel_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'last_updated_by': payload['last_updated_by'], - 'was_edited': payload['was_edited'], - 'from_': payload['from'], - 'body': payload['body'], - 'index': deserialize.integer(payload['index']), - 'type': payload['type'], - 'media': payload['media'], - 'url': payload['url'], - } + :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"]) - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], - } + return self._version.stream_async(page, limits["limit"]) - @property - def _proxy(self): + def list( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: MessageContext for this MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageContext - """ - 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'], + :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, ) - return self._context + ) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + async def list_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: """ - return self._properties['sid'] + 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. - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + :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, + ) + ] - @property - def attributes(self): + 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: """ - :returns: The attributes - :rtype: unicode - """ - return self._properties['attributes'] + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] + :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 - @property - def to(self): - """ - :returns: The to - :rtype: unicode + :returns: Page of MessageInstance """ - return self._properties['to'] + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def channel_sid(self): - """ - :returns: The channel_sid - :rtype: unicode - """ - return self._properties['channel_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + headers["Accept"] = "application/json" - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) - @property - def last_updated_by(self): - """ - :returns: The last_updated_by - :rtype: unicode + 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: """ - return self._properties['last_updated_by'] + Asynchronously retrieve a single page of MessageInstance records from the API. + Request is executed immediately - @property - def was_edited(self): - """ - :returns: The was_edited - :rtype: bool - """ - return self._properties['was_edited'] + :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 - @property - def from_(self): - """ - :returns: The from - :rtype: unicode + :returns: Page of MessageInstance """ - return self._properties['from_'] + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def body(self): - """ - :returns: The body - :rtype: unicode - """ - return self._properties['body'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def index(self): - """ - :returns: The index - :rtype: unicode - """ - return self._properties['index'] + headers["Accept"] = "application/json" - @property - def type(self): - """ - :returns: The type - :rtype: unicode - """ - return self._properties['type'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) - @property - def media(self): + def get_page(self, target_url: str) -> MessagePage: """ - :returns: The media - :rtype: dict - """ - return self._properties['media'] + Retrieve a specific page of MessageInstance records from the API. + Request is executed immediately - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] + :param target_url: API-generated URL for the requested results page - def fetch(self): + :returns: Page of MessageInstance """ - Fetch a MessageInstance + response = self._version.domain.twilio.request("GET", target_url) + return MessagePage(self._version, response, self._solution) - :returns: Fetched MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance + async def get_page_async(self, target_url: str) -> MessagePage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of MessageInstance records from the API. + Request is executed immediately - def delete(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance """ - Deletes the MessageInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagePage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def get(self, sid: str) -> MessageContext: """ - return self._proxy.delete() + Constructs a MessageContext - def update(self, body=values.unset, attributes=values.unset, - date_created=values.unset, date_updated=values.unset, - last_updated_by=values.unset): + :param sid: The SID of the Message resource to update. """ - Update the MessageInstance + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - :param unicode body: The body - :param unicode attributes: The attributes - :param datetime date_created: The date_created - :param datetime date_updated: The date_updated - :param unicode last_updated_by: The last_updated_by + def __call__(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext - :returns: Updated MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance + :param sid: The SID of the Message resource to update. """ - return self._proxy.update( - body=body, - attributes=attributes, - date_created=date_created, - date_updated=date_updated, - last_updated_by=last_updated_by, + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 "".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 "".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 "" + + +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 "" diff --git a/twilio/rest/chat/v2/service/role.py b/twilio/rest/chat/v2/service/role.py index d0257a99f7..fef06436d0 100644 --- a/twilio/rest/chat/v2/service/role.py +++ b/twilio/rest/chat/v2/service/role.py @@ -1,460 +1,645 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 RoleList(ListResource): - """ """ +class RoleInstance(InstanceResource): - def __init__(self, version, service_sid): - """ - Initialize the RoleList + class RoleType(object): + CHANNEL = "channel" + DEPLOYMENT = "deployment" - :param Version version: Version that contains the resource - :param service_sid: The service_sid + """ + :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 - :returns: twilio.rest.chat.v2.service.role.RoleList - :rtype: twilio.rest.chat.v2.service.role.RoleList + @property + def _proxy(self) -> "RoleContext": """ - super(RoleList, self).__init__(version) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Roles'.format(**self._solution) + :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 create(self, friendly_name, type, permission): + def delete(self) -> bool: """ - Create a new RoleInstance + Deletes the RoleInstance - :param unicode friendly_name: The friendly_name - :param RoleInstance.RoleType type: The type - :param unicode permission: The permission - :returns: Newly created RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Type': type, - 'Permission': serialize.map(permission, lambda e: e), - }) + return self._proxy.delete() - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance - return RoleInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return await self._proxy.delete_async() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.role.RoleInstance] + def fetch(self) -> "RoleInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the RoleInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched RoleInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the RoleInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.role.RoleInstance] + :returns: The fetched RoleInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def update(self, permission: List[str]) -> "RoleInstance": """ - Retrieve a single page of RoleInstance records from the API. - Request is executed immediately + Update the RoleInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :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: Page of RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RolePage + :returns: The updated RoleInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + return self._proxy.update( + permission=permission, ) - return RolePage(self._version, response, self._solution) - - def get_page(self, target_url): + async def update_async(self, permission: List[str]) -> "RoleInstance": """ - Retrieve a specific page of RoleInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the RoleInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RolePage + :returns: The updated RoleInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + permission=permission, ) - return RolePage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a RoleContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - :param sid: The sid +class RoleContext(InstanceContext): - :returns: twilio.rest.chat.v2.service.role.RoleContext - :rtype: twilio.rest.chat.v2.service.role.RoleContext + def __init__(self, version: Version, service_sid: str, sid: str): """ - return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Initialize the RoleContext - def __call__(self, sid): + :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. """ - Constructs a RoleContext + super().__init__(version) - :param sid: The sid + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Roles/{sid}".format(**self._solution) - :returns: twilio.rest.chat.v2.service.role.RoleContext - :rtype: twilio.rest.chat.v2.service.role.RoleContext + def delete(self) -> bool: """ - return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Deletes the RoleInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class RolePage(Page): - """ """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, response, solution): + async def delete_async(self) -> bool: """ - Initialize the RolePage + Asynchronous coroutine that deletes the RoleInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :returns: twilio.rest.chat.v2.service.role.RolePage - :rtype: twilio.rest.chat.v2.service.role.RolePage + :returns: True if delete succeeds, False otherwise """ - super(RolePage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: """ - Build an instance of RoleInstance + Fetch the RoleInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v2.service.role.RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance + :returns: The fetched RoleInstance """ - return RoleInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def __repr__(self): - """ - Provide a friendly representation + headers = values.of({}) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Accept"] = "application/json" + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) -class RoleContext(InstanceContext): - """ """ + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - def __init__(self, version, service_sid, sid): + async def fetch_async(self) -> RoleInstance: """ - Initialize the RoleContext + Asynchronous coroutine to fetch the RoleInstance - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: The sid - :returns: twilio.rest.chat.v2.service.role.RoleContext - :rtype: twilio.rest.chat.v2.service.role.RoleContext + :returns: The fetched RoleInstance """ - super(RoleContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Roles/{sid}'.format(**self._solution) + 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 fetch(self): + def update(self, permission: List[str]) -> RoleInstance: """ - Fetch a 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: Fetched RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance + :returns: The updated RoleInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def update_async(self, permission: List[str]) -> RoleInstance: """ - Deletes the RoleInstance + Asynchronous coroutine to update the RoleInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :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`. - def update(self, permission): + :returns: The updated RoleInstance """ - Update the RoleInstance - :param unicode permission: The permission + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) - :returns: Updated RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance - """ - data = values.of({'Permission': serialize.map(permission, lambda e: e), }) + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class RoleInstance(InstanceResource): - """ """ +class RolePage(Page): - class RoleType(object): - CHANNEL = "channel" - DEPLOYMENT = "deployment" + def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: + """ + Build an instance of RoleInstance - def __init__(self, version, payload, service_sid, sid=None): + :param payload: Payload response from the API """ - Initialize the RoleInstance + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - :returns: twilio.rest.chat.v2.service.role.RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance + def __repr__(self) -> str: """ - super(RoleInstance, self).__init__(version) + Provide a friendly representation - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'friendly_name': payload['friendly_name'], - 'type': payload['type'], - 'permissions': payload['permissions'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - } + :returns: Machine friendly representation + """ + return "" - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context +class RoleList(ListResource): - :returns: RoleContext for this RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleContext + def __init__(self, version: Version, service_sid: str): """ - if self._context is None: - self._context = RoleContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + 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. - @property - def sid(self): """ - :returns: The sid - :rtype: unicode + 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: """ - return self._properties['sid'] + Create the RoleInstance - @property - def account_sid(self): + :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 """ - :returns: The account_sid - :rtype: unicode + + 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: """ - return self._properties['account_sid'] + Asynchronously create the RoleInstance - @property - def service_sid(self): + :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 """ - :returns: The service_sid - :rtype: unicode + + 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]: """ - return self._properties['service_sid'] + 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. - @property - def friendly_name(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The friendly_name - :rtype: unicode + 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]: """ - return self._properties['friendly_name'] + 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. - @property - def type(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The type - :rtype: RoleInstance.RoleType + 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]: """ - return self._properties['type'] + Lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def permissions(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The permissions - :rtype: unicode + 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]: """ - return self._properties['permissions'] + 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. - @property - def date_created(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The date_created - :rtype: datetime + 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: """ - return self._properties['date_created'] + Retrieve a single page of RoleInstance records from the API. + Request is executed immediately - @property - def date_updated(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The date_updated - :rtype: datetime + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page of RoleInstance records from the API. + Request is executed immediately - @property - def url(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The url - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of RoleInstance """ - Fetch a RoleInstance + response = self._version.domain.twilio.request("GET", target_url) + return RolePage(self._version, response, self._solution) - :returns: Fetched RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance + async def get_page_async(self, target_url: str) -> RolePage: """ - return self._proxy.fetch() + 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 - def delete(self): + :returns: Page of RoleInstance """ - Deletes the RoleInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return RolePage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def get(self, sid: str) -> RoleContext: """ - return self._proxy.delete() + Constructs a RoleContext - def update(self, permission): + :param sid: The SID of the Role resource to update. """ - Update the RoleInstance + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - :param unicode permission: The permission + def __call__(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext - :returns: Updated RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance + :param sid: The SID of the Role resource to update. """ - return self._proxy.update(permission, ) + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/chat/v2/service/user/__init__.py b/twilio/rest/chat/v2/service/user/__init__.py index c9b5085644..9fbde6feda 100644 --- a/twilio/rest/chat/v2/service/user/__init__.py +++ b/twilio/rest/chat/v2/service/user/__init__.py @@ -1,567 +1,804 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 UserList(ListResource): - """ """ +class UserInstance(InstanceResource): - def __init__(self, version, service_sid): - """ - Initialize the UserList + 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") - :param Version version: Version that contains the resource - :param service_sid: The service_sid + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[UserContext] = None - :returns: twilio.rest.chat.v2.service.user.UserList - :rtype: twilio.rest.chat.v2.service.user.UserList + @property + def _proxy(self) -> "UserContext": """ - super(UserList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Users'.format(**self._solution) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def create(self, identity, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset): + :returns: UserContext for this UserInstance """ - Create a new UserInstance - - :param unicode identity: The identity - :param unicode role_sid: The role_sid - :param unicode attributes: The attributes - :param unicode friendly_name: The friendly_name + if self._context is None: + self._context = UserContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: Newly created UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserInstance + def delete(self) -> bool: """ - data = values.of({ - 'Identity': identity, - 'RoleSid': role_sid, - 'Attributes': attributes, - 'FriendlyName': friendly_name, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + Deletes the UserInstance - return UserInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.user.UserInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the UserInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the UserInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.user.UserInstance] + :returns: The fetched UserInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_async(self) -> "UserInstance": """ - Retrieve a single page of UserInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the UserInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserPage + :returns: The fetched UserInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_async() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return UserPage(self._version, response, self._solution) - - def get_page(self, target_url): + 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": """ - Retrieve a specific page of UserInstance records from the API. - Request is executed immediately + Update the UserInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserPage + :returns: The updated UserInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, ) - return UserPage(self._version, response, self._solution) + 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, + ) - def get(self, sid): + @property + def user_bindings(self) -> UserBindingList: """ - Constructs a UserContext - - :param sid: The sid - - :returns: twilio.rest.chat.v2.service.user.UserContext - :rtype: twilio.rest.chat.v2.service.user.UserContext + Access the user_bindings """ - return UserContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.user_bindings - def __call__(self, sid): + @property + def user_channels(self) -> UserChannelList: """ - Constructs a UserContext - - :param sid: The sid - - :returns: twilio.rest.chat.v2.service.user.UserContext - :rtype: twilio.rest.chat.v2.service.user.UserContext + Access the user_channels """ - return UserContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.user_channels - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class UserPage(Page): - """ """ +class UserContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the UserPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid + Initialize the UserContext - :returns: twilio.rest.chat.v2.service.user.UserPage - :rtype: twilio.rest.chat.v2.service.user.UserPage + :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(UserPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of UserInstance + Deletes the UserInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v2.service.user.UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserInstance + :returns: True if delete succeeds, False otherwise """ - return UserInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the UserInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class UserContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, service_sid, sid): + def fetch(self) -> UserInstance: """ - Initialize the UserContext + Fetch the UserInstance - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: The sid - :returns: twilio.rest.chat.v2.service.user.UserContext - :rtype: twilio.rest.chat.v2.service.user.UserContext + :returns: The fetched UserInstance """ - super(UserContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Users/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._user_channels = None - self._user_bindings = None + headers["Accept"] = "application/json" - def fetch(self): + 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: """ - Fetch a UserInstance + Asynchronous coroutine to fetch the UserInstance + - :returns: Fetched UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserInstance + :returns: The fetched UserInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + 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: """ - Deletes the UserInstance + Update the UserInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :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. - def update(self, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset): + :returns: The updated UserInstance """ - Update the UserInstance - :param unicode role_sid: The role_sid - :param unicode attributes: The attributes - :param unicode friendly_name: The friendly_name + 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" - :returns: Updated UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserInstance - """ - data = values.of({'RoleSid': role_sid, 'Attributes': attributes, 'FriendlyName': friendly_name, }) + headers["Accept"] = "application/json" payload = self._version.update( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) return UserInstance( self._version, payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - @property - def user_channels(self): + 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: """ - Access the user_channels + 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: twilio.rest.chat.v2.service.user.user_channel.UserChannelList - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelList + :returns: The updated UserInstance """ - if self._user_channels is None: - self._user_channels = UserChannelList( - self._version, - service_sid=self._solution['service_sid'], - user_sid=self._solution['sid'], + + 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 ) - return self._user_channels + ): + 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): + def user_bindings(self) -> UserBindingList: """ Access the user_bindings - - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingList - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingList """ if self._user_bindings is None: self._user_bindings = UserBindingList( self._version, - service_sid=self._solution['service_sid'], - user_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) return self._user_bindings - def __repr__(self): + @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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class UserInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the UserInstance - - :returns: twilio.rest.chat.v2.service.user.UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserInstance - """ - super(UserInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'attributes': payload['attributes'], - 'friendly_name': payload['friendly_name'], - 'role_sid': payload['role_sid'], - 'identity': payload['identity'], - 'is_online': payload['is_online'], - 'is_notifiable': payload['is_notifiable'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'joined_channels_count': deserialize.integer(payload['joined_channels_count']), - 'links': payload['links'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } +class UserPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> UserInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of UserInstance - :returns: UserContext for this UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = UserContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def sid(self): + def __repr__(self) -> str: """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] - @property - def attributes(self): - """ - :returns: The attributes - :rtype: unicode - """ - return self._properties['attributes'] +class UserList(ListResource): - @property - def friendly_name(self): + def __init__(self, version: Version, service_sid: str): """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] + Initialize the UserList - @property - def role_sid(self): - """ - :returns: The role_sid - :rtype: unicode - """ - return self._properties['role_sid'] + :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. - @property - def identity(self): """ - :returns: The identity - :rtype: unicode - """ - return self._properties['identity'] + super().__init__(version) - @property - def is_online(self): - """ - :returns: The is_online - :rtype: bool - """ - return self._properties['is_online'] + # 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", + } + ) - @property - def is_notifiable(self): - """ - :returns: The is_notifiable - :rtype: bool - """ - return self._properties['is_notifiable'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def date_created(self): + 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]: """ - :returns: The date_created - :rtype: datetime + 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 """ - return self._properties['date_created'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def date_updated(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserInstance]: """ - :returns: The date_updated - :rtype: datetime + 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 """ - return self._properties['date_updated'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def joined_channels_count(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: """ - :returns: The joined_channels_count - :rtype: unicode + 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 self._properties['joined_channels_count'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def links(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: """ - :returns: The links - :rtype: unicode + 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 self._properties['links'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def url(self): + 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: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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) - def fetch(self): + 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: """ - Fetch a UserInstance + Asynchronously retrieve a single page of UserInstance records from the API. + Request is executed immediately - :returns: Fetched UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserInstance + :param page_token: PageToken provided by the API + :param page_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 """ - return self._proxy.fetch() + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" - def delete(self): + 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: """ - Deletes the UserInstance + Retrieve a specific page of UserInstance records from the API. + Request is executed immediately - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance """ - return self._proxy.delete() + response = self._version.domain.twilio.request("GET", target_url) + return UserPage(self._version, response, self._solution) - def update(self, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset): + async def get_page_async(self, target_url: str) -> UserPage: """ - Update the UserInstance + Asynchronously retrieve a specific page of UserInstance records from the API. + Request is executed immediately - :param unicode role_sid: The role_sid - :param unicode attributes: The attributes - :param unicode friendly_name: The friendly_name + :param target_url: API-generated URL for the requested results page - :returns: Updated UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserInstance + :returns: Page of UserInstance """ - return self._proxy.update(role_sid=role_sid, attributes=attributes, friendly_name=friendly_name, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserPage(self._version, response, self._solution) - @property - def user_channels(self): + def get(self, sid: str) -> UserContext: """ - Access the user_channels + Constructs a UserContext - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelList - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelList + :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 self._proxy.user_channels + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - @property - def user_bindings(self): + def __call__(self, sid: str) -> UserContext: """ - Access the user_bindings + Constructs a UserContext - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingList - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingList + :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 self._proxy.user_bindings + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/chat/v2/service/user/user_binding.py b/twilio/rest/chat/v2/service/user/user_binding.py index 47a7c6344f..8d79c551af 100644 --- a/twilio/rest/chat/v2/service/user/user_binding.py +++ b/twilio/rest/chat/v2/service/user/user_binding.py @@ -1,460 +1,552 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 UserBindingList(ListResource): - """ """ - - def __init__(self, version, service_sid, user_sid): - """ - Initialize the UserBindingList +class UserBindingInstance(InstanceResource): - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param user_sid: The user_sid + class BindingType(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingList - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingList - """ - super(UserBindingList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'service_sid': service_sid, 'user_sid': user_sid, } - self._uri = '/Services/{service_sid}/Users/{user_sid}/Bindings'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "sid": sid or self.sid, + } + self._context: Optional[UserBindingContext] = None - def stream(self, binding_type=values.unset, limit=None, page_size=None): + @property + def _proxy(self) -> "UserBindingContext": """ - 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. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param UserBindingInstance.BindingType binding_type: The binding_type - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the UserBindingInstance - page = self.page(binding_type=binding_type, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, binding_type=values.unset, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists UserBindingInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the UserBindingInstance - :param UserBindingInstance.BindingType binding_type: The binding_type - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(binding_type=binding_type, limit=limit, page_size=page_size, )) + return await self._proxy.delete_async() - def page(self, binding_type=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch(self) -> "UserBindingInstance": """ - Retrieve a single page of UserBindingInstance records from the API. - Request is executed immediately + Fetch the UserBindingInstance - :param UserBindingInstance.BindingType binding_type: The binding_type - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of UserBindingInstance - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingPage + :returns: The fetched UserBindingInstance """ - params = values.of({ - 'BindingType': serialize.map(binding_type, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + async def fetch_async(self) -> "UserBindingInstance": + """ + Asynchronous coroutine to fetch the UserBindingInstance - return UserBindingPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched UserBindingInstance """ - Retrieve a specific page of UserBindingInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_async() - :param str target_url: API-generated URL for the requested results page + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of UserBindingInstance - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingPage + :returns: Machine friendly representation """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - return UserBindingPage(self._version, response, self._solution) - def get(self, sid): - """ - Constructs a UserBindingContext +class UserBindingContext(InstanceContext): - :param sid: The sid + def __init__(self, version: Version, service_sid: str, user_sid: str, sid: str): + """ + Initialize the UserBindingContext - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext - :rtype: twilio.rest.chat.v2.service.user.user_binding.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. """ - return UserBindingContext( - self._version, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], - sid=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 __call__(self, sid): + def delete(self) -> bool: """ - Constructs a UserBindingContext + Deletes the UserBindingInstance - :param sid: The sid - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext + :returns: True if delete succeeds, False otherwise """ - return UserBindingContext( - self._version, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], - sid=sid, - ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the UserBindingInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class UserBindingPage(Page): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> UserBindingInstance: """ - Initialize the UserBindingPage + Fetch the UserBindingInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :param user_sid: The user_sid - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingPage - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingPage + :returns: The fetched UserBindingInstance """ - super(UserBindingPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): - """ - Build an instance of UserBindingInstance + headers["Accept"] = "application/json" - :param dict payload: Payload response from the API + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance - """ return UserBindingInstance( self._version, payload, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + async def fetch_async(self) -> UserBindingInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the UserBindingInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched UserBindingInstance """ - return '' + headers = values.of({}) -class UserBindingContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, service_sid, user_sid, sid): - """ - Initialize the UserBindingContext + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param user_sid: The user_sid - :param sid: The sid + return UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext + def __repr__(self) -> str: """ - super(UserBindingContext, self).__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) + Provide a friendly representation - def fetch(self): + :returns: Machine friendly representation """ - Fetch a UserBindingInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: Fetched UserBindingInstance - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance - """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) +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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], ) - def delete(self): - """ - Deletes the UserBindingInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" -class UserBindingInstance(InstanceResource): - """ """ +class UserBindingList(ListResource): - class BindingType(object): - GCM = "gcm" - APN = "apn" - FCM = "fcm" + def __init__(self, version: Version, service_sid: str, user_sid: str): + """ + Initialize the UserBindingList - def __init__(self, version, payload, service_sid, user_sid, sid=None): - """ - Initialize the UserBindingInstance - - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance - """ - super(UserBindingInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'endpoint': payload['endpoint'], - 'identity': payload['identity'], - 'user_sid': payload['user_sid'], - 'credential_sid': payload['credential_sid'], - 'binding_type': payload['binding_type'], - 'message_types': payload['message_types'], - 'url': payload['url'], - } + :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) - # Context - self._context = None + # Path Solution self._solution = { - 'service_sid': service_sid, - 'user_sid': user_sid, - 'sid': sid or self._properties['sid'], + "service_sid": service_sid, + "user_sid": user_sid, } + self._uri = "/Services/{service_sid}/Users/{user_sid}/Bindings".format( + **self._solution + ) - @property - def _proxy(self): + def stream( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserBindingInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: UserBindingContext for this UserBindingInstance - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext - """ - 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 + :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) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['sid'] + limits = self._version.read_limits(limit, page_size) + page = self.page(binding_type=binding_type, page_size=limits["page_size"]) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + return self._version.stream(page, limits["limit"]) - @property - def service_sid(self): + 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]: """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] + 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. - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + :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) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime + :returns: Generator that will yield up to limit results """ - return self._properties['date_updated'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + binding_type=binding_type, page_size=limits["page_size"] + ) - @property - def endpoint(self): - """ - :returns: The endpoint - :rtype: unicode - """ - return self._properties['endpoint'] + return self._version.stream_async(page, limits["limit"]) - @property - def identity(self): + def list( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserBindingInstance]: """ - :returns: The identity - :rtype: unicode - """ - return self._properties['identity'] + Lists UserBindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def user_sid(self): - """ - :returns: The user_sid - :rtype: unicode - """ - return self._properties['user_sid'] + :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, + ) + ) - @property - def credential_sid(self): + 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]: """ - :returns: The credential_sid - :rtype: unicode + 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: """ - return self._properties['credential_sid'] + Retrieve a single page of UserBindingInstance records from the API. + Request is executed immediately - @property - def binding_type(self): + :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 """ - :returns: The binding_type - :rtype: UserBindingInstance.BindingType + 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 """ - return self._properties['binding_type'] + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def message_types(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The message_types - :rtype: unicode + 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 """ - return self._properties['message_types'] + response = self._version.domain.twilio.request("GET", target_url) + return UserBindingPage(self._version, response, self._solution) - @property - def url(self): + async def get_page_async(self, target_url: str) -> UserBindingPage: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserBindingPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> UserBindingContext: """ - Fetch a UserBindingInstance + Constructs a UserBindingContext - :returns: Fetched UserBindingInstance - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance + :param sid: The SID of the User Binding resource to fetch. """ - return self._proxy.fetch() + return UserBindingContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=sid, + ) - def delete(self): + def __call__(self, sid: str) -> UserBindingContext: """ - Deletes the UserBindingInstance + Constructs a UserBindingContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The SID of the User Binding resource to fetch. """ - return self._proxy.delete() + return UserBindingContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/chat/v2/service/user/user_channel.py b/twilio/rest/chat/v2/service/user/user_channel.py index 7439674c9b..9fab357368 100644 --- a/twilio/rest/chat/v2/service/user/user_channel.py +++ b/twilio/rest/chat/v2/service/user/user_channel.py @@ -1,277 +1,708 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 UserChannelList(ListResource): - """ """ +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 - def __init__(self, version, service_sid, user_sid): + @property + def _proxy(self) -> "UserChannelContext": """ - Initialize the UserChannelList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param user_sid: The sid + :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 - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelList - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelList + def delete( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - super(UserChannelList, self).__init__(version) + Deletes the UserChannelInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'user_sid': user_sid, } - self._uri = '/Services/{service_sid}/Users/{user_sid}/Channels'.format(**self._solution) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the UserChannelInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance] + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "UserChannelInstance": + """ + Fetch the UserChannelInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + return self._proxy.fetch() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + async def fetch_async(self) -> "UserChannelInstance": + """ + Asynchronous coroutine to fetch the UserChannelInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance] + + :returns: The fetched UserChannelInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + 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": """ - Retrieve a single page of UserChannelInstance records from the API. - Request is executed immediately + Update the UserChannelInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :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: Page of UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelPage + :returns: The updated UserChannelInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.update( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) - response = self._version.page( - 'GET', - self._uri, - params=params, + 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, ) - return UserChannelPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get_page(self, target_url): + :returns: Machine friendly representation """ - Retrieve a specific page of UserChannelInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param str target_url: API-generated URL for the requested results page - :returns: Page of UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelPage +class UserChannelContext(InstanceContext): + + def __init__( + self, version: Version, service_sid: str, user_sid: str, channel_sid: str + ): """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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 + ) ) - return UserChannelPage(self._version, response, self._solution) + def delete( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the UserChannelInstance - def __repr__(self): + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) - :returns: Machine friendly representation - :rtype: str + 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: """ - return '' + Asynchronous coroutine that deletes the UserChannelInstance + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header -class UserChannelPage(Page): - """ """ + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) - def __init__(self, version, response, solution): + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserChannelInstance: """ - Initialize the UserChannelPage + Fetch the UserChannelInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :param user_sid: The sid - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelPage - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelPage + :returns: The fetched UserChannelInstance """ - super(UserChannelPage, self).__init__(version, response) - # Path Solution - self._solution = solution + 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"], + ) - def get_instance(self, payload): + async def fetch_async(self) -> UserChannelInstance: """ - Build an instance of UserChannelInstance + Asynchronous coroutine to fetch the UserChannelInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.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'], + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], ) - def __repr__(self): + 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 - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class UserChannelInstance(InstanceResource): - """ """ +class UserChannelPage(Page): - class ChannelStatus(object): - JOINED = "joined" - INVITED = "invited" - NOT_PARTICIPATING = "not_participating" + 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 __init__(self, version, payload, service_sid, user_sid): + def __repr__(self) -> str: """ - Initialize the UserChannelInstance + Provide a friendly representation - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance + :returns: Machine friendly representation """ - super(UserChannelInstance, self).__init__(version) + return "" - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'channel_sid': payload['channel_sid'], - 'member_sid': payload['member_sid'], - 'status': payload['status'], - 'last_consumed_message_index': deserialize.integer(payload['last_consumed_message_index']), - 'unread_messages_count': deserialize.integer(payload['unread_messages_count']), - 'links': payload['links'], + +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. - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'user_sid': user_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) - @property - def account_sid(self): + :returns: Generator that will yield up to limit results """ - :returns: The account_sid - :rtype: unicode + 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]: """ - return self._properties['account_sid'] + 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. - @property - def service_sid(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(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]: """ - :returns: The service_sid - :rtype: unicode + 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 self._properties['service_sid'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def channel_sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: """ - :returns: The channel_sid - :rtype: unicode + 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: """ - return self._properties['channel_sid'] + Retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately - @property - def member_sid(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The member_sid - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['member_sid'] + Asynchronously retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately - @property - def status(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The status - :rtype: UserChannelInstance.ChannelStatus + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['status'] + Retrieve a specific page of UserChannelInstance records from the API. + Request is executed immediately - @property - def last_consumed_message_index(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserChannelInstance """ - :returns: The last_consumed_message_index - :rtype: unicode + 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: """ - return self._properties['last_consumed_message_index'] + Asynchronously retrieve a specific page of UserChannelInstance records from the API. + Request is executed immediately - @property - def unread_messages_count(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserChannelInstance """ - :returns: The unread_messages_count - :rtype: unicode + 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: """ - return self._properties['unread_messages_count'] + Constructs a UserChannelContext - @property - def links(self): + :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`. """ - :returns: The links - :rtype: unicode + 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 self._properties['links'] + return UserChannelContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=channel_sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" 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 "" 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 "".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 "".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 "" 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 "" 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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "" 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 "".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 "".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 "" 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 "" + + +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 "" + + +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 "" 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 "" + + +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 "" + + +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 "" 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 "" 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 "" + + +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 "" + + +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=: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.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=: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(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=: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + 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=: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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=: + :param page_token: PageToken provided by the API + :param page_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=: + :param page_token: PageToken provided by the API + :param page_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 "" 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 "" + + +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 "" + + +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=: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.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=: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(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=: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + 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=: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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=: + :param page_token: PageToken provided by the API + :param page_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=: + :param page_token: PageToken provided by the API + :param page_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 "" 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 "" 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 "" 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 "".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 "".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 "" + + +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 "" 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 "" + + +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 "" + + +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 "" 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 "" + + +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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "" + + +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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 ( + "".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 "" 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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "" 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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "" 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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" diff --git a/twilio/rest/fax/__init__.py b/twilio/rest/fax/__init__.py deleted file mode 100644 index d7edde428f..0000000000 --- a/twilio/rest/fax/__init__.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base.domain import Domain -from twilio.rest.fax.v1 import V1 - - -class Fax(Domain): - - def __init__(self, twilio): - """ - Initialize the Fax Domain - - :returns: Domain for Fax - :rtype: twilio.rest.fax.Fax - """ - super(Fax, self).__init__(twilio) - - self.base_url = 'https://fax.twilio.com' - - # Versions - self._v1 = None - - @property - def v1(self): - """ - :returns: Version v1 of fax - :rtype: twilio.rest.fax.v1.V1 - """ - if self._v1 is None: - self._v1 = V1(self) - return self._v1 - - @property - def faxes(self): - """ - :rtype: twilio.rest.fax.v1.fax.FaxList - """ - return self.v1.faxes - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/fax/v1/__init__.py b/twilio/rest/fax/v1/__init__.py deleted file mode 100644 index 8ce0420d3f..0000000000 --- a/twilio/rest/fax/v1/__init__.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base.version import Version -from twilio.rest.fax.v1.fax import FaxList - - -class V1(Version): - - def __init__(self, domain): - """ - Initialize the V1 version of Fax - - :returns: V1 version of Fax - :rtype: twilio.rest.fax.v1.V1.V1 - """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._faxes = None - - @property - def faxes(self): - """ - :rtype: twilio.rest.fax.v1.fax.FaxList - """ - if self._faxes is None: - self._faxes = FaxList(self) - return self._faxes - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/fax/v1/fax/__init__.py b/twilio/rest/fax/v1/fax/__init__.py deleted file mode 100644 index 79200eaf07..0000000000 --- a/twilio/rest/fax/v1/fax/__init__.py +++ /dev/null @@ -1,628 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import serialize -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.page import Page -from twilio.rest.fax.v1.fax.fax_media import FaxMediaList - - -class FaxList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version): - """ - Initialize the FaxList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.fax.v1.fax.FaxList - :rtype: twilio.rest.fax.v1.fax.FaxList - """ - super(FaxList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Faxes'.format(**self._solution) - - def stream(self, from_=values.unset, to=values.unset, - date_created_on_or_before=values.unset, - date_created_after=values.unset, limit=None, page_size=None): - """ - Streams FaxInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param unicode from_: Include only faxes sent from - :param unicode to: Include only faxes sent to - :param datetime date_created_on_or_before: Include only faxes created on or before - :param datetime date_created_after: Include only faxes created after - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.fax.v1.fax.FaxInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page( - from_=from_, - to=to, - date_created_on_or_before=date_created_on_or_before, - date_created_after=date_created_after, - page_size=limits['page_size'], - ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, from_=values.unset, to=values.unset, - date_created_on_or_before=values.unset, - date_created_after=values.unset, limit=None, page_size=None): - """ - Lists FaxInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param unicode from_: Include only faxes sent from - :param unicode to: Include only faxes sent to - :param datetime date_created_on_or_before: Include only faxes created on or before - :param datetime date_created_after: Include only faxes created after - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.fax.v1.fax.FaxInstance] - """ - return list(self.stream( - from_=from_, - to=to, - date_created_on_or_before=date_created_on_or_before, - date_created_after=date_created_after, - limit=limit, - page_size=page_size, - )) - - def page(self, from_=values.unset, to=values.unset, - date_created_on_or_before=values.unset, - date_created_after=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of FaxInstance records from the API. - Request is executed immediately - - :param unicode from_: Include only faxes sent from - :param unicode to: Include only faxes sent to - :param datetime date_created_on_or_before: Include only faxes created on or before - :param datetime date_created_after: Include only faxes created after - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of FaxInstance - :rtype: twilio.rest.fax.v1.fax.FaxPage - """ - params = values.of({ - 'From': from_, - 'To': to, - 'DateCreatedOnOrBefore': serialize.iso8601_datetime(date_created_on_or_before), - 'DateCreatedAfter': serialize.iso8601_datetime(date_created_after), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return FaxPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of FaxInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of FaxInstance - :rtype: twilio.rest.fax.v1.fax.FaxPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return FaxPage(self._version, response, self._solution) - - def create(self, to, media_url, quality=values.unset, - status_callback=values.unset, from_=values.unset, - sip_auth_username=values.unset, sip_auth_password=values.unset, - store_media=values.unset, ttl=values.unset): - """ - Create a new FaxInstance - - :param unicode to: The phone number or SIP address to send the fax to - :param unicode media_url: URL that points to the fax media - :param FaxInstance.Quality quality: The quality of this fax - :param unicode status_callback: URL for fax status callbacks - :param unicode from_: Twilio number from which to originate the fax - :param unicode sip_auth_username: Username for SIP authentication - :param unicode sip_auth_password: Password for SIP authentication - :param bool store_media: Whether or not to store media - :param unicode ttl: How many minutes to attempt a fax - - :returns: Newly created FaxInstance - :rtype: twilio.rest.fax.v1.fax.FaxInstance - """ - data = values.of({ - 'To': to, - 'MediaUrl': media_url, - 'Quality': quality, - 'StatusCallback': status_callback, - 'From': from_, - 'SipAuthUsername': sip_auth_username, - 'SipAuthPassword': sip_auth_password, - 'StoreMedia': store_media, - 'Ttl': ttl, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return FaxInstance(self._version, payload, ) - - def get(self, sid): - """ - Constructs a FaxContext - - :param sid: A string that uniquely identifies this fax. - - :returns: twilio.rest.fax.v1.fax.FaxContext - :rtype: twilio.rest.fax.v1.fax.FaxContext - """ - return FaxContext(self._version, sid=sid, ) - - def __call__(self, sid): - """ - Constructs a FaxContext - - :param sid: A string that uniquely identifies this fax. - - :returns: twilio.rest.fax.v1.fax.FaxContext - :rtype: twilio.rest.fax.v1.fax.FaxContext - """ - return FaxContext(self._version, sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class FaxPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, response, solution): - """ - Initialize the FaxPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.fax.v1.fax.FaxPage - :rtype: twilio.rest.fax.v1.fax.FaxPage - """ - super(FaxPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of FaxInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.fax.v1.fax.FaxInstance - :rtype: twilio.rest.fax.v1.fax.FaxInstance - """ - return FaxInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class FaxContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, sid): - """ - Initialize the FaxContext - - :param Version version: Version that contains the resource - :param sid: A string that uniquely identifies this fax. - - :returns: twilio.rest.fax.v1.fax.FaxContext - :rtype: twilio.rest.fax.v1.fax.FaxContext - """ - super(FaxContext, self).__init__(version) - - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Faxes/{sid}'.format(**self._solution) - - # Dependents - self._media = None - - def fetch(self): - """ - Fetch a FaxInstance - - :returns: Fetched FaxInstance - :rtype: twilio.rest.fax.v1.fax.FaxInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return FaxInstance(self._version, payload, sid=self._solution['sid'], ) - - def update(self, status=values.unset): - """ - Update the FaxInstance - - :param FaxInstance.UpdateStatus status: The updated status of this fax - - :returns: Updated FaxInstance - :rtype: twilio.rest.fax.v1.fax.FaxInstance - """ - data = values.of({'Status': status, }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return FaxInstance(self._version, payload, sid=self._solution['sid'], ) - - def delete(self): - """ - Deletes the FaxInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - @property - def media(self): - """ - Access the media - - :returns: twilio.rest.fax.v1.fax.fax_media.FaxMediaList - :rtype: twilio.rest.fax.v1.fax.fax_media.FaxMediaList - """ - if self._media is None: - self._media = FaxMediaList(self._version, fax_sid=self._solution['sid'], ) - return self._media - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class FaxInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - class Direction(object): - INBOUND = "inbound" - OUTBOUND = "outbound" - - class Quality(object): - STANDARD = "standard" - FINE = "fine" - SUPERFINE = "superfine" - - class Status(object): - QUEUED = "queued" - PROCESSING = "processing" - SENDING = "sending" - DELIVERED = "delivered" - RECEIVING = "receiving" - RECEIVED = "received" - NO_ANSWER = "no-answer" - BUSY = "busy" - FAILED = "failed" - CANCELED = "canceled" - - class UpdateStatus(object): - CANCELED = "canceled" - - def __init__(self, version, payload, sid=None): - """ - Initialize the FaxInstance - - :returns: twilio.rest.fax.v1.fax.FaxInstance - :rtype: twilio.rest.fax.v1.fax.FaxInstance - """ - super(FaxInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'from_': payload['from'], - 'to': payload['to'], - 'quality': payload['quality'], - 'media_sid': payload['media_sid'], - 'media_url': payload['media_url'], - 'num_pages': deserialize.integer(payload['num_pages']), - 'duration': deserialize.integer(payload['duration']), - 'status': payload['status'], - 'direction': payload['direction'], - 'api_version': payload['api_version'], - 'price': deserialize.decimal(payload['price']), - 'price_unit': payload['price_unit'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'links': payload['links'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: FaxContext for this FaxInstance - :rtype: twilio.rest.fax.v1.fax.FaxContext - """ - if self._context is None: - self._context = FaxContext(self._version, sid=self._solution['sid'], ) - return self._context - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this fax. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def account_sid(self): - """ - :returns: Account SID - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def from_(self): - """ - :returns: The party that sent the fax - :rtype: unicode - """ - return self._properties['from_'] - - @property - def to(self): - """ - :returns: The party that received the fax - :rtype: unicode - """ - return self._properties['to'] - - @property - def quality(self): - """ - :returns: The quality of this fax - :rtype: FaxInstance.Quality - """ - return self._properties['quality'] - - @property - def media_sid(self): - """ - :returns: Media SID - :rtype: unicode - """ - return self._properties['media_sid'] - - @property - def media_url(self): - """ - :returns: URL pointing to fax media - :rtype: unicode - """ - return self._properties['media_url'] - - @property - def num_pages(self): - """ - :returns: Number of pages - :rtype: unicode - """ - return self._properties['num_pages'] - - @property - def duration(self): - """ - :returns: The time taken to transmit the fax - :rtype: unicode - """ - return self._properties['duration'] - - @property - def status(self): - """ - :returns: The status of this fax - :rtype: FaxInstance.Status - """ - return self._properties['status'] - - @property - def direction(self): - """ - :returns: The direction of this fax - :rtype: FaxInstance.Direction - """ - return self._properties['direction'] - - @property - def api_version(self): - """ - :returns: The API version used - :rtype: unicode - """ - return self._properties['api_version'] - - @property - def price(self): - """ - :returns: Fax transmission price - :rtype: unicode - """ - return self._properties['price'] - - @property - def price_unit(self): - """ - :returns: Currency used for billing - :rtype: unicode - """ - return self._properties['price_unit'] - - @property - def date_created(self): - """ - :returns: The date this fax was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date this fax was updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def links(self): - """ - :returns: Nested resource URLs - :rtype: unicode - """ - return self._properties['links'] - - @property - def url(self): - """ - :returns: The URL of this resource - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch a FaxInstance - - :returns: Fetched FaxInstance - :rtype: twilio.rest.fax.v1.fax.FaxInstance - """ - return self._proxy.fetch() - - def update(self, status=values.unset): - """ - Update the FaxInstance - - :param FaxInstance.UpdateStatus status: The updated status of this fax - - :returns: Updated FaxInstance - :rtype: twilio.rest.fax.v1.fax.FaxInstance - """ - return self._proxy.update(status=status, ) - - def delete(self): - """ - Deletes the FaxInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - @property - def media(self): - """ - Access the media - - :returns: twilio.rest.fax.v1.fax.fax_media.FaxMediaList - :rtype: twilio.rest.fax.v1.fax.fax_media.FaxMediaList - """ - return self._proxy.media - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/fax/v1/fax/fax_media.py b/twilio/rest/fax/v1/fax/fax_media.py deleted file mode 100644 index de427737dc..0000000000 --- a/twilio/rest/fax/v1/fax/fax_media.py +++ /dev/null @@ -1,381 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page - - -class FaxMediaList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, fax_sid): - """ - Initialize the FaxMediaList - - :param Version version: Version that contains the resource - :param fax_sid: Fax SID - - :returns: twilio.rest.fax.v1.fax.fax_media.FaxMediaList - :rtype: twilio.rest.fax.v1.fax.fax_media.FaxMediaList - """ - super(FaxMediaList, self).__init__(version) - - # Path Solution - self._solution = {'fax_sid': fax_sid, } - self._uri = '/Faxes/{fax_sid}/Media'.format(**self._solution) - - def stream(self, limit=None, page_size=None): - """ - Streams FaxMediaInstance records from the API as a generator stream. - This operation lazily loads 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 limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.fax.v1.fax.fax_media.FaxMediaInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists FaxMediaInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.fax.v1.fax.fax_media.FaxMediaInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of FaxMediaInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of FaxMediaInstance - :rtype: twilio.rest.fax.v1.fax.fax_media.FaxMediaPage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return FaxMediaPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of FaxMediaInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of FaxMediaInstance - :rtype: twilio.rest.fax.v1.fax.fax_media.FaxMediaPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return FaxMediaPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a FaxMediaContext - - :param sid: A string that uniquely identifies this fax media - - :returns: twilio.rest.fax.v1.fax.fax_media.FaxMediaContext - :rtype: twilio.rest.fax.v1.fax.fax_media.FaxMediaContext - """ - return FaxMediaContext(self._version, fax_sid=self._solution['fax_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a FaxMediaContext - - :param sid: A string that uniquely identifies this fax media - - :returns: twilio.rest.fax.v1.fax.fax_media.FaxMediaContext - :rtype: twilio.rest.fax.v1.fax.fax_media.FaxMediaContext - """ - return FaxMediaContext(self._version, fax_sid=self._solution['fax_sid'], sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class FaxMediaPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, response, solution): - """ - Initialize the FaxMediaPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param fax_sid: Fax SID - - :returns: twilio.rest.fax.v1.fax.fax_media.FaxMediaPage - :rtype: twilio.rest.fax.v1.fax.fax_media.FaxMediaPage - """ - super(FaxMediaPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of FaxMediaInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.fax.v1.fax.fax_media.FaxMediaInstance - :rtype: twilio.rest.fax.v1.fax.fax_media.FaxMediaInstance - """ - return FaxMediaInstance(self._version, payload, fax_sid=self._solution['fax_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class FaxMediaContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, fax_sid, sid): - """ - Initialize the FaxMediaContext - - :param Version version: Version that contains the resource - :param fax_sid: Fax SID - :param sid: A string that uniquely identifies this fax media - - :returns: twilio.rest.fax.v1.fax.fax_media.FaxMediaContext - :rtype: twilio.rest.fax.v1.fax.fax_media.FaxMediaContext - """ - super(FaxMediaContext, self).__init__(version) - - # Path Solution - self._solution = {'fax_sid': fax_sid, 'sid': sid, } - self._uri = '/Faxes/{fax_sid}/Media/{sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch a FaxMediaInstance - - :returns: Fetched FaxMediaInstance - :rtype: twilio.rest.fax.v1.fax.fax_media.FaxMediaInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return FaxMediaInstance( - self._version, - payload, - fax_sid=self._solution['fax_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the FaxMediaInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class FaxMediaInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, payload, fax_sid, sid=None): - """ - Initialize the FaxMediaInstance - - :returns: twilio.rest.fax.v1.fax.fax_media.FaxMediaInstance - :rtype: twilio.rest.fax.v1.fax.fax_media.FaxMediaInstance - """ - super(FaxMediaInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'fax_sid': payload['fax_sid'], - 'content_type': payload['content_type'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = {'fax_sid': fax_sid, 'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: FaxMediaContext for this FaxMediaInstance - :rtype: twilio.rest.fax.v1.fax.fax_media.FaxMediaContext - """ - if self._context is None: - self._context = FaxMediaContext( - self._version, - fax_sid=self._solution['fax_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this fax media - :rtype: unicode - """ - return self._properties['sid'] - - @property - def account_sid(self): - """ - :returns: Account SID - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def fax_sid(self): - """ - :returns: Fax SID - :rtype: unicode - """ - return self._properties['fax_sid'] - - @property - def content_type(self): - """ - :returns: Media content type - :rtype: unicode - """ - return self._properties['content_type'] - - @property - def date_created(self): - """ - :returns: The date this fax media was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date this fax media was updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def url(self): - """ - :returns: The URL of this resource - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch a FaxMediaInstance - - :returns: Fetched FaxMediaInstance - :rtype: twilio.rest.fax.v1.fax.fax_media.FaxMediaInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the FaxMediaInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) 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 "" 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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "" + + +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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "" + + +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 "" + + +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 "" 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 "" + + +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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "" + + +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 "" + + +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 "" 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 "" + + +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 "" + + +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 "" 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 "" + + +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 "" 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 "" + + +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 "" 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 "" + + +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 "" + + +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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" 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 "" + + +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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "" 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 "".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 "".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 "" 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 "" + + +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 "" 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 "" 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 "" 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 "".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 "".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 "" 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 "" 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 "" 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 "".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 "".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 "" 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 "" + + +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 "" + + +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 "" 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 "" + + +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 "" 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 "" + + +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 "" 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 "" 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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" 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 "".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 "" + + +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 "" 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 "".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 "" + + +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 "" 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 "" + + +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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "" + + +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 "" + + +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 "" 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 "" 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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "" + + +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 "" 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 "" diff --git a/twilio/rest/ip_messaging/__init__.py b/twilio/rest/ip_messaging/__init__.py index a425384eef..61158f8e6a 100644 --- a/twilio/rest/ip_messaging/__init__.py +++ b/twilio/rest/ip_messaging/__init__.py @@ -1,72 +1,25 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" +from warnings import warn -from twilio.base.domain import Domain -from twilio.rest.ip_messaging.v1 import V1 -from twilio.rest.ip_messaging.v2 import V2 +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(Domain): - - def __init__(self, twilio): - """ - Initialize the IpMessaging Domain - - :returns: Domain for IpMessaging - :rtype: twilio.rest.ip_messaging.IpMessaging - """ - super(IpMessaging, self).__init__(twilio) - - self.base_url = 'https://ip-messaging.twilio.com' - - # Versions - self._v1 = None - self._v2 = None - +class IpMessaging(IpMessagingBase): @property - def v1(self): - """ - :returns: Version v1 of ip_messaging - :rtype: twilio.rest.ip_messaging.v1.V1 - """ - if self._v1 is None: - self._v1 = V1(self) - return self._v1 - - @property - def v2(self): - """ - :returns: Version v2 of ip_messaging - :rtype: twilio.rest.ip_messaging.v2.V2 - """ - if self._v2 is None: - self._v2 = V2(self) - return self._v2 - - @property - def credentials(self): - """ - :rtype: twilio.rest.chat.v2.credential.CredentialList - """ + def credentials(self) -> CredentialList: + warn( + "credentials is deprecated. Use v2.credentials instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v2.credentials @property - def services(self): - """ - :rtype: twilio.rest.chat.v2.service.ServiceList - """ + def services(self) -> ServiceList: + warn( + "services is deprecated. Use v2.services instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v2.services - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/ip_messaging/v1/__init__.py b/twilio/rest/ip_messaging/v1/__init__.py index 811bc829a4..d1f40c791f 100644 --- a/twilio/rest/ip_messaging/v1/__init__.py +++ b/twilio/rest/ip_messaging/v1/__init__.py @@ -1,53 +1,51 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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): + def __init__(self, domain: Domain): """ Initialize the V1 version of IpMessaging - :returns: V1 version of IpMessaging - :rtype: twilio.rest.ip_messaging.v1.V1.V1 + :param domain: The Twilio.ip_messaging domain """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._credentials = None - self._services = None + super().__init__(domain, "v1") + self._credentials: Optional[CredentialList] = None + self._services: Optional[ServiceList] = None @property - def credentials(self): - """ - :rtype: twilio.rest.chat.v1.credential.CredentialList - """ + def credentials(self) -> CredentialList: if self._credentials is None: self._credentials = CredentialList(self) return self._credentials @property - def services(self): - """ - :rtype: twilio.rest.chat.v1.service.ServiceList - """ + def services(self) -> ServiceList: if self._services is None: self._services = ServiceList(self) return self._services - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/ip_messaging/v1/credential.py b/twilio/rest/ip_messaging/v1/credential.py index e5d99ace2d..4aa6d3fc63 100644 --- a/twilio/rest/ip_messaging/v1/credential.py +++ b/twilio/rest/ip_messaging/v1/credential.py @@ -1,472 +1,711 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 CredentialList(ListResource): - """ """ - - def __init__(self, version): - """ - Initialize the CredentialList +class CredentialInstance(InstanceResource): - :param Version version: Version that contains the resource + class PushService(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" - :returns: twilio.rest.chat.v1.credential.CredentialList - :rtype: twilio.rest.chat.v1.credential.CredentialList - """ - super(CredentialList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {} - self._uri = '/Credentials'.format(**self._solution) + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CredentialContext] = None - def stream(self, limit=None, page_size=None): + @property + def _proxy(self) -> "CredentialContext": """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.credential.CredentialInstance] + :returns: CredentialContext for this CredentialInstance """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def list(self, limit=None, page_size=None): + def delete(self) -> bool: """ - Lists CredentialInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the CredentialInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.credential.CredentialInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.delete() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def delete_async(self) -> bool: """ - Retrieve a single page of CredentialInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the CredentialInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialPage + :returns: True if delete succeeds, False otherwise """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + return await self._proxy.delete_async() - return CredentialPage(self._version, response, self._solution) - - def get_page(self, target_url): + def fetch(self) -> "CredentialInstance": """ - Retrieve a specific page of CredentialInstance records from the API. - Request is executed immediately + Fetch the CredentialInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialPage + :returns: The fetched CredentialInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return CredentialPage(self._version, response, self._solution) + return self._proxy.fetch() - def create(self, type, friendly_name=values.unset, certificate=values.unset, - private_key=values.unset, sandbox=values.unset, api_key=values.unset, - secret=values.unset): + async def fetch_async(self) -> "CredentialInstance": """ - Create a new CredentialInstance + Asynchronous coroutine to fetch the CredentialInstance - :param CredentialInstance.PushService type: The type - :param unicode friendly_name: The friendly_name - :param unicode certificate: The certificate - :param unicode private_key: The private_key - :param bool sandbox: The sandbox - :param unicode api_key: The api_key - :param unicode secret: The secret - :returns: Newly created CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance + :returns: The fetched CredentialInstance """ - data = values.of({ - 'Type': type, - 'FriendlyName': friendly_name, - 'Certificate': certificate, - 'PrivateKey': private_key, - 'Sandbox': sandbox, - 'ApiKey': api_key, - 'Secret': secret, - }) + return await self._proxy.fetch_async() - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return CredentialInstance(self._version, payload, ) - - def get(self, 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": """ - Constructs a CredentialContext + Update the CredentialInstance - :param sid: The sid + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: - :returns: twilio.rest.chat.v1.credential.CredentialContext - :rtype: twilio.rest.chat.v1.credential.CredentialContext + :returns: The updated CredentialInstance """ - return CredentialContext(self._version, sid=sid, ) + return self._proxy.update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - def __call__(self, 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": """ - Constructs a CredentialContext + Asynchronous coroutine to update the CredentialInstance - :param sid: The sid + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: - :returns: twilio.rest.chat.v1.credential.CredentialContext - :rtype: twilio.rest.chat.v1.credential.CredentialContext + :returns: The updated CredentialInstance """ - return CredentialContext(self._version, sid=sid, ) + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class CredentialPage(Page): - """ """ +class CredentialContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the CredentialPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the CredentialContext - :returns: twilio.rest.chat.v1.credential.CredentialPage - :rtype: twilio.rest.chat.v1.credential.CredentialPage + :param version: Version that contains the resource + :param sid: """ - super(CredentialPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) - def get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of CredentialInstance + Deletes the CredentialInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v1.credential.CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance + :returns: True if delete succeeds, False otherwise """ - return CredentialInstance(self._version, payload, ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the CredentialInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class CredentialContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, sid): + def fetch(self) -> CredentialInstance: """ - Initialize the CredentialContext + Fetch the CredentialInstance - :param Version version: Version that contains the resource - :param sid: The sid - :returns: twilio.rest.chat.v1.credential.CredentialContext - :rtype: twilio.rest.chat.v1.credential.CredentialContext + :returns: The fetched CredentialInstance """ - super(CredentialContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Credentials/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialInstance: """ - Fetch a CredentialInstance + Asynchronous coroutine to fetch the CredentialInstance - :returns: Fetched CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance + + :returns: The fetched CredentialInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], ) + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def update(self, friendly_name=values.unset, certificate=values.unset, - private_key=values.unset, sandbox=values.unset, api_key=values.unset, - secret=values.unset): + 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 unicode friendly_name: The friendly_name - :param unicode certificate: The certificate - :param unicode private_key: The private_key - :param bool sandbox: The sandbox - :param unicode api_key: The api_key - :param unicode secret: The secret - - :returns: Updated CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Certificate': certificate, - 'PrivateKey': private_key, - 'Sandbox': sandbox, - 'ApiKey': api_key, - 'Secret': secret, - }) + :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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) - return CredentialInstance(self._version, payload, sid=self._solution['sid'], ) + 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({}) - def delete(self): - """ - Deletes the CredentialInstance + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + headers["Accept"] = "application/json" - def __repr__(self): + 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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class CredentialInstance(InstanceResource): - """ """ +class CredentialPage(Page): - class PushService(object): - GCM = "gcm" - APN = "apn" - FCM = "fcm" + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: + """ + Build an instance of CredentialInstance - def __init__(self, version, payload, sid=None): + :param payload: Payload response from the API """ - Initialize the CredentialInstance + return CredentialInstance(self._version, payload) - :returns: twilio.rest.chat.v1.credential.CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance + def __repr__(self) -> str: """ - super(CredentialInstance, self).__init__(version) + Provide a friendly representation - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'friendly_name': payload['friendly_name'], - 'type': payload['type'], - 'sandbox': payload['sandbox'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - } + :returns: Machine friendly representation + """ + return "" - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context +class CredentialList(ListResource): - :returns: CredentialContext for this CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialContext + def __init__(self, version: Version): """ - if self._context is None: - self._context = CredentialContext(self._version, sid=self._solution['sid'], ) - return self._context + Initialize the CredentialList + + :param version: Version that contains the resource - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode """ - return self._properties['sid'] + super().__init__(version) - @property - def account_sid(self): + 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: """ - :returns: The account_sid - :rtype: unicode + Create the CredentialInstance + + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The created CredentialInstance """ - return self._properties['account_sid'] - @property - def friendly_name(self): + 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]: """ - :returns: The friendly_name - :rtype: unicode + 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 """ - return self._properties['friendly_name'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def type(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialInstance]: """ - :returns: The type - :rtype: CredentialInstance.PushService + 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 """ - return self._properties['type'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def sandbox(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: """ - :returns: The sandbox - :rtype: unicode + 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 self._properties['sandbox'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def date_created(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: """ - :returns: The date_created - :rtype: datetime + 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: """ - return self._properties['date_created'] + Retrieve a single page of CredentialInstance records from the API. + Request is executed immediately - @property - def date_updated(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The date_updated - :rtype: datetime + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page of CredentialInstance records from the API. + Request is executed immediately - @property - def url(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The url - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['url'] + Retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance """ - Fetch a CredentialInstance + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) - :returns: Fetched CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance + async def get_page_async(self, target_url: str) -> CredentialPage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately - def update(self, friendly_name=values.unset, certificate=values.unset, - private_key=values.unset, sandbox=values.unset, api_key=values.unset, - secret=values.unset): + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance """ - Update the CredentialInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response) - :param unicode friendly_name: The friendly_name - :param unicode certificate: The certificate - :param unicode private_key: The private_key - :param bool sandbox: The sandbox - :param unicode api_key: The api_key - :param unicode secret: The secret + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext - :returns: Updated CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance + :param sid: """ - return self._proxy.update( - friendly_name=friendly_name, - certificate=certificate, - private_key=private_key, - sandbox=sandbox, - api_key=api_key, - secret=secret, - ) + return CredentialContext(self._version, sid=sid) - def delete(self): + def __call__(self, sid: str) -> CredentialContext: """ - Deletes the CredentialInstance + Constructs a CredentialContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: """ - return self._proxy.delete() + return CredentialContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/ip_messaging/v1/service/__init__.py b/twilio/rest/ip_messaging/v1/service/__init__.py index 76df879e4a..3a77cf765e 100644 --- a/twilio/rest/ip_messaging/v1/service/__init__.py +++ b/twilio/rest/ip_messaging/v1/service/__init__.py @@ -1,1027 +1,1359 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 ServiceList(ListResource): - """ """ +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 - def __init__(self, version): + @property + def _proxy(self) -> "ServiceContext": """ - Initialize the ServiceList - - :param Version version: Version that contains the resource + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: twilio.rest.chat.v1.service.ServiceList - :rtype: twilio.rest.chat.v1.service.ServiceList + :returns: ServiceContext for this ServiceInstance """ - super(ServiceList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Services'.format(**self._solution) + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def create(self, friendly_name): + def delete(self) -> bool: """ - Create a new ServiceInstance + Deletes the ServiceInstance - :param unicode friendly_name: The friendly_name - :returns: Newly created ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({'FriendlyName': friendly_name, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return ServiceInstance(self._version, payload, ) + return self._proxy.delete() - def stream(self, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - 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. + Asynchronous coroutine that deletes the ServiceInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.ServiceInstance] + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the ServiceInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.ServiceInstance] + :returns: The fetched ServiceInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + 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": """ - Retrieve a single page of ServiceInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + Update the ServiceInstance - :returns: Page of ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServicePage + :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 """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + 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, ) - return ServicePage(self._version, response, self._solution) + 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, + ) - def get_page(self, target_url): + @property + def channels(self) -> ChannelList: """ - Retrieve a specific page of ServiceInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServicePage + Access the channels """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ServicePage(self._version, response, self._solution) + return self._proxy.channels - def get(self, sid): + @property + def roles(self) -> RoleList: """ - Constructs a ServiceContext - - :param sid: The sid - - :returns: twilio.rest.chat.v1.service.ServiceContext - :rtype: twilio.rest.chat.v1.service.ServiceContext + Access the roles """ - return ServiceContext(self._version, sid=sid, ) + return self._proxy.roles - def __call__(self, sid): + @property + def users(self) -> UserList: """ - Constructs a ServiceContext - - :param sid: The sid - - :returns: twilio.rest.chat.v1.service.ServiceContext - :rtype: twilio.rest.chat.v1.service.ServiceContext + Access the users """ - return ServiceContext(self._version, sid=sid, ) + return self._proxy.users - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ServicePage(Page): - """ """ +class ServiceContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the ServicePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the ServiceContext - :returns: twilio.rest.chat.v1.service.ServicePage - :rtype: twilio.rest.chat.v1.service.ServicePage + :param version: Version that contains the resource + :param sid: """ - super(ServicePage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) - def get_instance(self, payload): + self._channels: Optional[ChannelList] = None + self._roles: Optional[RoleList] = None + self._users: Optional[UserList] = None + + def delete(self) -> bool: """ - Build an instance of ServiceInstance + Deletes the ServiceInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v1.service.ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceInstance + :returns: True if delete succeeds, False otherwise """ - return ServiceInstance(self._version, payload, ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the ServiceInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class ServiceContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, sid): + def fetch(self) -> ServiceInstance: """ - Initialize the ServiceContext + Fetch the ServiceInstance - :param Version version: Version that contains the resource - :param sid: The sid - :returns: twilio.rest.chat.v1.service.ServiceContext - :rtype: twilio.rest.chat.v1.service.ServiceContext + :returns: The fetched ServiceInstance """ - super(ServiceContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Services/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - # Dependents - self._channels = None - self._roles = None - self._users = None + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: """ - Fetch a ServiceInstance + Asynchronous coroutine to fetch the ServiceInstance + - :returns: Fetched ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceInstance + :returns: The fetched ServiceInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) + headers = values.of({}) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" - def delete(self): - """ - Deletes the ServiceInstance + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def update(self, friendly_name=values.unset, - default_service_role_sid=values.unset, - default_channel_role_sid=values.unset, - default_channel_creator_role_sid=values.unset, - read_status_enabled=values.unset, reachability_enabled=values.unset, - typing_indicator_timeout=values.unset, - consumption_report_interval=values.unset, - notifications_new_message_enabled=values.unset, - notifications_new_message_template=values.unset, - notifications_added_to_channel_enabled=values.unset, - notifications_added_to_channel_template=values.unset, - notifications_removed_from_channel_enabled=values.unset, - notifications_removed_from_channel_template=values.unset, - notifications_invited_to_channel_enabled=values.unset, - notifications_invited_to_channel_template=values.unset, - pre_webhook_url=values.unset, post_webhook_url=values.unset, - webhook_method=values.unset, webhook_filters=values.unset, - webhooks_on_message_send_url=values.unset, - webhooks_on_message_send_method=values.unset, - webhooks_on_message_send_format=values.unset, - webhooks_on_message_update_url=values.unset, - webhooks_on_message_update_method=values.unset, - webhooks_on_message_update_format=values.unset, - webhooks_on_message_remove_url=values.unset, - webhooks_on_message_remove_method=values.unset, - webhooks_on_message_remove_format=values.unset, - webhooks_on_channel_add_url=values.unset, - webhooks_on_channel_add_method=values.unset, - webhooks_on_channel_add_format=values.unset, - webhooks_on_channel_destroy_url=values.unset, - webhooks_on_channel_destroy_method=values.unset, - webhooks_on_channel_destroy_format=values.unset, - webhooks_on_channel_update_url=values.unset, - webhooks_on_channel_update_method=values.unset, - webhooks_on_channel_update_format=values.unset, - webhooks_on_member_add_url=values.unset, - webhooks_on_member_add_method=values.unset, - webhooks_on_member_add_format=values.unset, - webhooks_on_member_remove_url=values.unset, - webhooks_on_member_remove_method=values.unset, - webhooks_on_member_remove_format=values.unset, - webhooks_on_message_sent_url=values.unset, - webhooks_on_message_sent_method=values.unset, - webhooks_on_message_sent_format=values.unset, - webhooks_on_message_updated_url=values.unset, - webhooks_on_message_updated_method=values.unset, - webhooks_on_message_updated_format=values.unset, - webhooks_on_message_removed_url=values.unset, - webhooks_on_message_removed_method=values.unset, - webhooks_on_message_removed_format=values.unset, - webhooks_on_channel_added_url=values.unset, - webhooks_on_channel_added_method=values.unset, - webhooks_on_channel_added_format=values.unset, - webhooks_on_channel_destroyed_url=values.unset, - webhooks_on_channel_destroyed_method=values.unset, - webhooks_on_channel_destroyed_format=values.unset, - webhooks_on_channel_updated_url=values.unset, - webhooks_on_channel_updated_method=values.unset, - webhooks_on_channel_updated_format=values.unset, - webhooks_on_member_added_url=values.unset, - webhooks_on_member_added_method=values.unset, - webhooks_on_member_added_format=values.unset, - webhooks_on_member_removed_url=values.unset, - webhooks_on_member_removed_method=values.unset, - webhooks_on_member_removed_format=values.unset, - limits_channel_members=values.unset, - limits_user_channels=values.unset): + 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 unicode friendly_name: The friendly_name - :param unicode default_service_role_sid: The default_service_role_sid - :param unicode default_channel_role_sid: The default_channel_role_sid - :param unicode default_channel_creator_role_sid: The default_channel_creator_role_sid - :param bool read_status_enabled: The read_status_enabled - :param bool reachability_enabled: The reachability_enabled - :param unicode typing_indicator_timeout: The typing_indicator_timeout - :param unicode consumption_report_interval: The consumption_report_interval - :param bool notifications_new_message_enabled: The notifications.new_message.enabled - :param unicode notifications_new_message_template: The notifications.new_message.template - :param bool notifications_added_to_channel_enabled: The notifications.added_to_channel.enabled - :param unicode notifications_added_to_channel_template: The notifications.added_to_channel.template - :param bool notifications_removed_from_channel_enabled: The notifications.removed_from_channel.enabled - :param unicode notifications_removed_from_channel_template: The notifications.removed_from_channel.template - :param bool notifications_invited_to_channel_enabled: The notifications.invited_to_channel.enabled - :param unicode notifications_invited_to_channel_template: The notifications.invited_to_channel.template - :param unicode pre_webhook_url: The pre_webhook_url - :param unicode post_webhook_url: The post_webhook_url - :param unicode webhook_method: The webhook_method - :param unicode webhook_filters: The webhook_filters - :param unicode webhooks_on_message_send_url: The webhooks.on_message_send.url - :param unicode webhooks_on_message_send_method: The webhooks.on_message_send.method - :param unicode webhooks_on_message_send_format: The webhooks.on_message_send.format - :param unicode webhooks_on_message_update_url: The webhooks.on_message_update.url - :param unicode webhooks_on_message_update_method: The webhooks.on_message_update.method - :param unicode webhooks_on_message_update_format: The webhooks.on_message_update.format - :param unicode webhooks_on_message_remove_url: The webhooks.on_message_remove.url - :param unicode webhooks_on_message_remove_method: The webhooks.on_message_remove.method - :param unicode webhooks_on_message_remove_format: The webhooks.on_message_remove.format - :param unicode webhooks_on_channel_add_url: The webhooks.on_channel_add.url - :param unicode webhooks_on_channel_add_method: The webhooks.on_channel_add.method - :param unicode webhooks_on_channel_add_format: The webhooks.on_channel_add.format - :param unicode webhooks_on_channel_destroy_url: The webhooks.on_channel_destroy.url - :param unicode webhooks_on_channel_destroy_method: The webhooks.on_channel_destroy.method - :param unicode webhooks_on_channel_destroy_format: The webhooks.on_channel_destroy.format - :param unicode webhooks_on_channel_update_url: The webhooks.on_channel_update.url - :param unicode webhooks_on_channel_update_method: The webhooks.on_channel_update.method - :param unicode webhooks_on_channel_update_format: The webhooks.on_channel_update.format - :param unicode webhooks_on_member_add_url: The webhooks.on_member_add.url - :param unicode webhooks_on_member_add_method: The webhooks.on_member_add.method - :param unicode webhooks_on_member_add_format: The webhooks.on_member_add.format - :param unicode webhooks_on_member_remove_url: The webhooks.on_member_remove.url - :param unicode webhooks_on_member_remove_method: The webhooks.on_member_remove.method - :param unicode webhooks_on_member_remove_format: The webhooks.on_member_remove.format - :param unicode webhooks_on_message_sent_url: The webhooks.on_message_sent.url - :param unicode webhooks_on_message_sent_method: The webhooks.on_message_sent.method - :param unicode webhooks_on_message_sent_format: The webhooks.on_message_sent.format - :param unicode webhooks_on_message_updated_url: The webhooks.on_message_updated.url - :param unicode webhooks_on_message_updated_method: The webhooks.on_message_updated.method - :param unicode webhooks_on_message_updated_format: The webhooks.on_message_updated.format - :param unicode webhooks_on_message_removed_url: The webhooks.on_message_removed.url - :param unicode webhooks_on_message_removed_method: The webhooks.on_message_removed.method - :param unicode webhooks_on_message_removed_format: The webhooks.on_message_removed.format - :param unicode webhooks_on_channel_added_url: The webhooks.on_channel_added.url - :param unicode webhooks_on_channel_added_method: The webhooks.on_channel_added.method - :param unicode webhooks_on_channel_added_format: The webhooks.on_channel_added.format - :param unicode webhooks_on_channel_destroyed_url: The webhooks.on_channel_destroyed.url - :param unicode webhooks_on_channel_destroyed_method: The webhooks.on_channel_destroyed.method - :param unicode webhooks_on_channel_destroyed_format: The webhooks.on_channel_destroyed.format - :param unicode webhooks_on_channel_updated_url: The webhooks.on_channel_updated.url - :param unicode webhooks_on_channel_updated_method: The webhooks.on_channel_updated.method - :param unicode webhooks_on_channel_updated_format: The webhooks.on_channel_updated.format - :param unicode webhooks_on_member_added_url: The webhooks.on_member_added.url - :param unicode webhooks_on_member_added_method: The webhooks.on_member_added.method - :param unicode webhooks_on_member_added_format: The webhooks.on_member_added.format - :param unicode webhooks_on_member_removed_url: The webhooks.on_member_removed.url - :param unicode webhooks_on_member_removed_method: The webhooks.on_member_removed.method - :param unicode webhooks_on_member_removed_format: The webhooks.on_member_removed.format - :param unicode limits_channel_members: The limits.channel_members - :param unicode limits_user_channels: The limits.user_channels - - :returns: Updated ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'DefaultServiceRoleSid': default_service_role_sid, - 'DefaultChannelRoleSid': default_channel_role_sid, - 'DefaultChannelCreatorRoleSid': default_channel_creator_role_sid, - 'ReadStatusEnabled': read_status_enabled, - 'ReachabilityEnabled': reachability_enabled, - 'TypingIndicatorTimeout': typing_indicator_timeout, - 'ConsumptionReportInterval': consumption_report_interval, - 'Notifications.NewMessage.Enabled': notifications_new_message_enabled, - 'Notifications.NewMessage.Template': notifications_new_message_template, - 'Notifications.AddedToChannel.Enabled': notifications_added_to_channel_enabled, - 'Notifications.AddedToChannel.Template': notifications_added_to_channel_template, - 'Notifications.RemovedFromChannel.Enabled': notifications_removed_from_channel_enabled, - 'Notifications.RemovedFromChannel.Template': notifications_removed_from_channel_template, - 'Notifications.InvitedToChannel.Enabled': 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.OnMessageSend.Format': webhooks_on_message_send_format, - 'Webhooks.OnMessageUpdate.Url': webhooks_on_message_update_url, - 'Webhooks.OnMessageUpdate.Method': webhooks_on_message_update_method, - 'Webhooks.OnMessageUpdate.Format': webhooks_on_message_update_format, - 'Webhooks.OnMessageRemove.Url': webhooks_on_message_remove_url, - 'Webhooks.OnMessageRemove.Method': webhooks_on_message_remove_method, - 'Webhooks.OnMessageRemove.Format': webhooks_on_message_remove_format, - 'Webhooks.OnChannelAdd.Url': webhooks_on_channel_add_url, - 'Webhooks.OnChannelAdd.Method': webhooks_on_channel_add_method, - 'Webhooks.OnChannelAdd.Format': webhooks_on_channel_add_format, - 'Webhooks.OnChannelDestroy.Url': webhooks_on_channel_destroy_url, - 'Webhooks.OnChannelDestroy.Method': webhooks_on_channel_destroy_method, - 'Webhooks.OnChannelDestroy.Format': webhooks_on_channel_destroy_format, - 'Webhooks.OnChannelUpdate.Url': webhooks_on_channel_update_url, - 'Webhooks.OnChannelUpdate.Method': webhooks_on_channel_update_method, - 'Webhooks.OnChannelUpdate.Format': webhooks_on_channel_update_format, - 'Webhooks.OnMemberAdd.Url': webhooks_on_member_add_url, - 'Webhooks.OnMemberAdd.Method': webhooks_on_member_add_method, - 'Webhooks.OnMemberAdd.Format': webhooks_on_member_add_format, - 'Webhooks.OnMemberRemove.Url': webhooks_on_member_remove_url, - 'Webhooks.OnMemberRemove.Method': webhooks_on_member_remove_method, - 'Webhooks.OnMemberRemove.Format': webhooks_on_member_remove_format, - 'Webhooks.OnMessageSent.Url': webhooks_on_message_sent_url, - 'Webhooks.OnMessageSent.Method': webhooks_on_message_sent_method, - 'Webhooks.OnMessageSent.Format': webhooks_on_message_sent_format, - 'Webhooks.OnMessageUpdated.Url': webhooks_on_message_updated_url, - 'Webhooks.OnMessageUpdated.Method': webhooks_on_message_updated_method, - 'Webhooks.OnMessageUpdated.Format': webhooks_on_message_updated_format, - 'Webhooks.OnMessageRemoved.Url': webhooks_on_message_removed_url, - 'Webhooks.OnMessageRemoved.Method': webhooks_on_message_removed_method, - 'Webhooks.OnMessageRemoved.Format': webhooks_on_message_removed_format, - 'Webhooks.OnChannelAdded.Url': webhooks_on_channel_added_url, - 'Webhooks.OnChannelAdded.Method': webhooks_on_channel_added_method, - 'Webhooks.OnChannelAdded.Format': webhooks_on_channel_added_format, - 'Webhooks.OnChannelDestroyed.Url': webhooks_on_channel_destroyed_url, - 'Webhooks.OnChannelDestroyed.Method': webhooks_on_channel_destroyed_method, - 'Webhooks.OnChannelDestroyed.Format': webhooks_on_channel_destroyed_format, - 'Webhooks.OnChannelUpdated.Url': webhooks_on_channel_updated_url, - 'Webhooks.OnChannelUpdated.Method': webhooks_on_channel_updated_method, - 'Webhooks.OnChannelUpdated.Format': webhooks_on_channel_updated_format, - 'Webhooks.OnMemberAdded.Url': webhooks_on_member_added_url, - 'Webhooks.OnMemberAdded.Method': webhooks_on_member_added_method, - 'Webhooks.OnMemberAdded.Format': webhooks_on_member_added_format, - 'Webhooks.OnMemberRemoved.Url': webhooks_on_member_removed_url, - 'Webhooks.OnMemberRemoved.Method': webhooks_on_member_removed_method, - 'Webhooks.OnMemberRemoved.Format': webhooks_on_member_removed_format, - 'Limits.ChannelMembers': limits_channel_members, - 'Limits.UserChannels': limits_user_channels, - }) + :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( - 'POST', - self._uri, - data=data, + 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'], ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) @property - def channels(self): + def channels(self) -> ChannelList: """ Access the channels - - :returns: twilio.rest.chat.v1.service.channel.ChannelList - :rtype: twilio.rest.chat.v1.service.channel.ChannelList """ if self._channels is None: - self._channels = ChannelList(self._version, service_sid=self._solution['sid'], ) + self._channels = ChannelList( + self._version, + self._solution["sid"], + ) return self._channels @property - def roles(self): + def roles(self) -> RoleList: """ Access the roles - - :returns: twilio.rest.chat.v1.service.role.RoleList - :rtype: twilio.rest.chat.v1.service.role.RoleList """ if self._roles is None: - self._roles = RoleList(self._version, service_sid=self._solution['sid'], ) + self._roles = RoleList( + self._version, + self._solution["sid"], + ) return self._roles @property - def users(self): + def users(self) -> UserList: """ Access the users - - :returns: twilio.rest.chat.v1.service.user.UserList - :rtype: twilio.rest.chat.v1.service.user.UserList """ if self._users is None: - self._users = UserList(self._version, service_sid=self._solution['sid'], ) + self._users = UserList( + self._version, + self._solution["sid"], + ) return self._users - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ServiceInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, sid=None): - """ - Initialize the ServiceInstance - - :returns: twilio.rest.chat.v1.service.ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceInstance - """ - super(ServiceInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'friendly_name': payload['friendly_name'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'default_service_role_sid': payload['default_service_role_sid'], - 'default_channel_role_sid': payload['default_channel_role_sid'], - 'default_channel_creator_role_sid': payload['default_channel_creator_role_sid'], - 'read_status_enabled': payload['read_status_enabled'], - 'reachability_enabled': payload['reachability_enabled'], - 'typing_indicator_timeout': deserialize.integer(payload['typing_indicator_timeout']), - 'consumption_report_interval': deserialize.integer(payload['consumption_report_interval']), - 'limits': payload['limits'], - 'webhooks': payload['webhooks'], - 'pre_webhook_url': payload['pre_webhook_url'], - 'post_webhook_url': payload['post_webhook_url'], - 'webhook_method': payload['webhook_method'], - 'webhook_filters': payload['webhook_filters'], - 'notifications': payload['notifications'], - 'url': payload['url'], - 'links': payload['links'], - } - - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } +class ServicePage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of ServiceInstance - :returns: ServiceContext for this ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = ServiceContext(self._version, sid=self._solution['sid'], ) - return self._context + return ServiceInstance(self._version, payload) - @property - def sid(self): + def __repr__(self) -> str: """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] +class ServiceList(ListResource): - @property - def date_updated(self): + def __init__(self, version: Version): """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + Initialize the ServiceList - @property - def default_service_role_sid(self): - """ - :returns: The default_service_role_sid - :rtype: unicode - """ - return self._properties['default_service_role_sid'] + :param version: Version that contains the resource - @property - def default_channel_role_sid(self): - """ - :returns: The default_channel_role_sid - :rtype: unicode """ - return self._properties['default_channel_role_sid'] + super().__init__(version) - @property - def default_channel_creator_role_sid(self): - """ - :returns: The default_channel_creator_role_sid - :rtype: unicode - """ - return self._properties['default_channel_creator_role_sid'] + self._uri = "/Services" - @property - def read_status_enabled(self): - """ - :returns: The read_status_enabled - :rtype: bool + def create(self, friendly_name: str) -> ServiceInstance: """ - return self._properties['read_status_enabled'] + Create the ServiceInstance - @property - def reachability_enabled(self): - """ - :returns: The reachability_enabled - :rtype: bool - """ - return self._properties['reachability_enabled'] + :param friendly_name: - @property - def typing_indicator_timeout(self): + :returns: The created ServiceInstance """ - :returns: The typing_indicator_timeout - :rtype: unicode - """ - return self._properties['typing_indicator_timeout'] - @property - def consumption_report_interval(self): - """ - :returns: The consumption_report_interval - :rtype: unicode - """ - return self._properties['consumption_report_interval'] + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def limits(self): - """ - :returns: The limits - :rtype: dict - """ - return self._properties['limits'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def webhooks(self): - """ - :returns: The webhooks - :rtype: dict - """ - return self._properties['webhooks'] + headers["Accept"] = "application/json" - @property - def pre_webhook_url(self): - """ - :returns: The pre_webhook_url - :rtype: unicode - """ - return self._properties['pre_webhook_url'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def post_webhook_url(self): - """ - :returns: The post_webhook_url - :rtype: unicode - """ - return self._properties['post_webhook_url'] + return ServiceInstance(self._version, payload) - @property - def webhook_method(self): + async def create_async(self, friendly_name: str) -> ServiceInstance: """ - :returns: The webhook_method - :rtype: unicode - """ - return self._properties['webhook_method'] + Asynchronously create the ServiceInstance - @property - def webhook_filters(self): + :param friendly_name: + + :returns: The created ServiceInstance """ - :returns: The webhook_filters - :rtype: unicode + + 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]: """ - return self._properties['webhook_filters'] + 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. - @property - def notifications(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The notifications - :rtype: dict + 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]: """ - return self._properties['notifications'] + 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. - @property - def url(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The url - :rtype: unicode + 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]: """ - return self._properties['url'] + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def links(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The links - :rtype: unicode + 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]: """ - return self._properties['links'] + 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. - def fetch(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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: """ - Fetch a ServiceInstance + 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: Fetched ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceInstance + :returns: Page of ServiceInstance """ - return self._proxy.fetch() + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - def delete(self): + headers = values.of({"Content-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: """ - Deletes the ServiceInstance + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param page_token: PageToken provided by the API + :param page_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 """ - return self._proxy.delete() + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def update(self, friendly_name=values.unset, - default_service_role_sid=values.unset, - default_channel_role_sid=values.unset, - default_channel_creator_role_sid=values.unset, - read_status_enabled=values.unset, reachability_enabled=values.unset, - typing_indicator_timeout=values.unset, - consumption_report_interval=values.unset, - notifications_new_message_enabled=values.unset, - notifications_new_message_template=values.unset, - notifications_added_to_channel_enabled=values.unset, - notifications_added_to_channel_template=values.unset, - notifications_removed_from_channel_enabled=values.unset, - notifications_removed_from_channel_template=values.unset, - notifications_invited_to_channel_enabled=values.unset, - notifications_invited_to_channel_template=values.unset, - pre_webhook_url=values.unset, post_webhook_url=values.unset, - webhook_method=values.unset, webhook_filters=values.unset, - webhooks_on_message_send_url=values.unset, - webhooks_on_message_send_method=values.unset, - webhooks_on_message_send_format=values.unset, - webhooks_on_message_update_url=values.unset, - webhooks_on_message_update_method=values.unset, - webhooks_on_message_update_format=values.unset, - webhooks_on_message_remove_url=values.unset, - webhooks_on_message_remove_method=values.unset, - webhooks_on_message_remove_format=values.unset, - webhooks_on_channel_add_url=values.unset, - webhooks_on_channel_add_method=values.unset, - webhooks_on_channel_add_format=values.unset, - webhooks_on_channel_destroy_url=values.unset, - webhooks_on_channel_destroy_method=values.unset, - webhooks_on_channel_destroy_format=values.unset, - webhooks_on_channel_update_url=values.unset, - webhooks_on_channel_update_method=values.unset, - webhooks_on_channel_update_format=values.unset, - webhooks_on_member_add_url=values.unset, - webhooks_on_member_add_method=values.unset, - webhooks_on_member_add_format=values.unset, - webhooks_on_member_remove_url=values.unset, - webhooks_on_member_remove_method=values.unset, - webhooks_on_member_remove_format=values.unset, - webhooks_on_message_sent_url=values.unset, - webhooks_on_message_sent_method=values.unset, - webhooks_on_message_sent_format=values.unset, - webhooks_on_message_updated_url=values.unset, - webhooks_on_message_updated_method=values.unset, - webhooks_on_message_updated_format=values.unset, - webhooks_on_message_removed_url=values.unset, - webhooks_on_message_removed_method=values.unset, - webhooks_on_message_removed_format=values.unset, - webhooks_on_channel_added_url=values.unset, - webhooks_on_channel_added_method=values.unset, - webhooks_on_channel_added_format=values.unset, - webhooks_on_channel_destroyed_url=values.unset, - webhooks_on_channel_destroyed_method=values.unset, - webhooks_on_channel_destroyed_format=values.unset, - webhooks_on_channel_updated_url=values.unset, - webhooks_on_channel_updated_method=values.unset, - webhooks_on_channel_updated_format=values.unset, - webhooks_on_member_added_url=values.unset, - webhooks_on_member_added_method=values.unset, - webhooks_on_member_added_format=values.unset, - webhooks_on_member_removed_url=values.unset, - webhooks_on_member_removed_method=values.unset, - webhooks_on_member_removed_format=values.unset, - limits_channel_members=values.unset, - limits_user_channels=values.unset): + 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: """ - Update the ServiceInstance + 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 - :param unicode friendly_name: The friendly_name - :param unicode default_service_role_sid: The default_service_role_sid - :param unicode default_channel_role_sid: The default_channel_role_sid - :param unicode default_channel_creator_role_sid: The default_channel_creator_role_sid - :param bool read_status_enabled: The read_status_enabled - :param bool reachability_enabled: The reachability_enabled - :param unicode typing_indicator_timeout: The typing_indicator_timeout - :param unicode consumption_report_interval: The consumption_report_interval - :param bool notifications_new_message_enabled: The notifications.new_message.enabled - :param unicode notifications_new_message_template: The notifications.new_message.template - :param bool notifications_added_to_channel_enabled: The notifications.added_to_channel.enabled - :param unicode notifications_added_to_channel_template: The notifications.added_to_channel.template - :param bool notifications_removed_from_channel_enabled: The notifications.removed_from_channel.enabled - :param unicode notifications_removed_from_channel_template: The notifications.removed_from_channel.template - :param bool notifications_invited_to_channel_enabled: The notifications.invited_to_channel.enabled - :param unicode notifications_invited_to_channel_template: The notifications.invited_to_channel.template - :param unicode pre_webhook_url: The pre_webhook_url - :param unicode post_webhook_url: The post_webhook_url - :param unicode webhook_method: The webhook_method - :param unicode webhook_filters: The webhook_filters - :param unicode webhooks_on_message_send_url: The webhooks.on_message_send.url - :param unicode webhooks_on_message_send_method: The webhooks.on_message_send.method - :param unicode webhooks_on_message_send_format: The webhooks.on_message_send.format - :param unicode webhooks_on_message_update_url: The webhooks.on_message_update.url - :param unicode webhooks_on_message_update_method: The webhooks.on_message_update.method - :param unicode webhooks_on_message_update_format: The webhooks.on_message_update.format - :param unicode webhooks_on_message_remove_url: The webhooks.on_message_remove.url - :param unicode webhooks_on_message_remove_method: The webhooks.on_message_remove.method - :param unicode webhooks_on_message_remove_format: The webhooks.on_message_remove.format - :param unicode webhooks_on_channel_add_url: The webhooks.on_channel_add.url - :param unicode webhooks_on_channel_add_method: The webhooks.on_channel_add.method - :param unicode webhooks_on_channel_add_format: The webhooks.on_channel_add.format - :param unicode webhooks_on_channel_destroy_url: The webhooks.on_channel_destroy.url - :param unicode webhooks_on_channel_destroy_method: The webhooks.on_channel_destroy.method - :param unicode webhooks_on_channel_destroy_format: The webhooks.on_channel_destroy.format - :param unicode webhooks_on_channel_update_url: The webhooks.on_channel_update.url - :param unicode webhooks_on_channel_update_method: The webhooks.on_channel_update.method - :param unicode webhooks_on_channel_update_format: The webhooks.on_channel_update.format - :param unicode webhooks_on_member_add_url: The webhooks.on_member_add.url - :param unicode webhooks_on_member_add_method: The webhooks.on_member_add.method - :param unicode webhooks_on_member_add_format: The webhooks.on_member_add.format - :param unicode webhooks_on_member_remove_url: The webhooks.on_member_remove.url - :param unicode webhooks_on_member_remove_method: The webhooks.on_member_remove.method - :param unicode webhooks_on_member_remove_format: The webhooks.on_member_remove.format - :param unicode webhooks_on_message_sent_url: The webhooks.on_message_sent.url - :param unicode webhooks_on_message_sent_method: The webhooks.on_message_sent.method - :param unicode webhooks_on_message_sent_format: The webhooks.on_message_sent.format - :param unicode webhooks_on_message_updated_url: The webhooks.on_message_updated.url - :param unicode webhooks_on_message_updated_method: The webhooks.on_message_updated.method - :param unicode webhooks_on_message_updated_format: The webhooks.on_message_updated.format - :param unicode webhooks_on_message_removed_url: The webhooks.on_message_removed.url - :param unicode webhooks_on_message_removed_method: The webhooks.on_message_removed.method - :param unicode webhooks_on_message_removed_format: The webhooks.on_message_removed.format - :param unicode webhooks_on_channel_added_url: The webhooks.on_channel_added.url - :param unicode webhooks_on_channel_added_method: The webhooks.on_channel_added.method - :param unicode webhooks_on_channel_added_format: The webhooks.on_channel_added.format - :param unicode webhooks_on_channel_destroyed_url: The webhooks.on_channel_destroyed.url - :param unicode webhooks_on_channel_destroyed_method: The webhooks.on_channel_destroyed.method - :param unicode webhooks_on_channel_destroyed_format: The webhooks.on_channel_destroyed.format - :param unicode webhooks_on_channel_updated_url: The webhooks.on_channel_updated.url - :param unicode webhooks_on_channel_updated_method: The webhooks.on_channel_updated.method - :param unicode webhooks_on_channel_updated_format: The webhooks.on_channel_updated.format - :param unicode webhooks_on_member_added_url: The webhooks.on_member_added.url - :param unicode webhooks_on_member_added_method: The webhooks.on_member_added.method - :param unicode webhooks_on_member_added_format: The webhooks.on_member_added.format - :param unicode webhooks_on_member_removed_url: The webhooks.on_member_removed.url - :param unicode webhooks_on_member_removed_method: The webhooks.on_member_removed.method - :param unicode webhooks_on_member_removed_format: The webhooks.on_member_removed.format - :param unicode limits_channel_members: The limits.channel_members - :param unicode limits_user_channels: The limits.user_channels - - :returns: Updated ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceInstance + :returns: Page of 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_send_format=webhooks_on_message_send_format, - webhooks_on_message_update_url=webhooks_on_message_update_url, - webhooks_on_message_update_method=webhooks_on_message_update_method, - webhooks_on_message_update_format=webhooks_on_message_update_format, - webhooks_on_message_remove_url=webhooks_on_message_remove_url, - webhooks_on_message_remove_method=webhooks_on_message_remove_method, - webhooks_on_message_remove_format=webhooks_on_message_remove_format, - webhooks_on_channel_add_url=webhooks_on_channel_add_url, - webhooks_on_channel_add_method=webhooks_on_channel_add_method, - webhooks_on_channel_add_format=webhooks_on_channel_add_format, - webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, - webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, - webhooks_on_channel_destroy_format=webhooks_on_channel_destroy_format, - webhooks_on_channel_update_url=webhooks_on_channel_update_url, - webhooks_on_channel_update_method=webhooks_on_channel_update_method, - webhooks_on_channel_update_format=webhooks_on_channel_update_format, - webhooks_on_member_add_url=webhooks_on_member_add_url, - webhooks_on_member_add_method=webhooks_on_member_add_method, - webhooks_on_member_add_format=webhooks_on_member_add_format, - webhooks_on_member_remove_url=webhooks_on_member_remove_url, - webhooks_on_member_remove_method=webhooks_on_member_remove_method, - webhooks_on_member_remove_format=webhooks_on_member_remove_format, - webhooks_on_message_sent_url=webhooks_on_message_sent_url, - webhooks_on_message_sent_method=webhooks_on_message_sent_method, - webhooks_on_message_sent_format=webhooks_on_message_sent_format, - webhooks_on_message_updated_url=webhooks_on_message_updated_url, - webhooks_on_message_updated_method=webhooks_on_message_updated_method, - webhooks_on_message_updated_format=webhooks_on_message_updated_format, - webhooks_on_message_removed_url=webhooks_on_message_removed_url, - webhooks_on_message_removed_method=webhooks_on_message_removed_method, - webhooks_on_message_removed_format=webhooks_on_message_removed_format, - webhooks_on_channel_added_url=webhooks_on_channel_added_url, - webhooks_on_channel_added_method=webhooks_on_channel_added_method, - webhooks_on_channel_added_format=webhooks_on_channel_added_format, - webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, - webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, - webhooks_on_channel_destroyed_format=webhooks_on_channel_destroyed_format, - webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, - webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, - webhooks_on_channel_updated_format=webhooks_on_channel_updated_format, - webhooks_on_member_added_url=webhooks_on_member_added_url, - webhooks_on_member_added_method=webhooks_on_member_added_method, - webhooks_on_member_added_format=webhooks_on_member_added_format, - webhooks_on_member_removed_url=webhooks_on_member_removed_url, - webhooks_on_member_removed_method=webhooks_on_member_removed_method, - webhooks_on_member_removed_format=webhooks_on_member_removed_format, - limits_channel_members=limits_channel_members, - limits_user_channels=limits_user_channels, - ) + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) - @property - def channels(self): + async def get_page_async(self, target_url: str) -> ServicePage: """ - Access the channels + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately - :returns: twilio.rest.chat.v1.service.channel.ChannelList - :rtype: twilio.rest.chat.v1.service.channel.ChannelList + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance """ - return self._proxy.channels + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) - @property - def roles(self): + def get(self, sid: str) -> ServiceContext: """ - Access the roles + Constructs a ServiceContext - :returns: twilio.rest.chat.v1.service.role.RoleList - :rtype: twilio.rest.chat.v1.service.role.RoleList + :param sid: """ - return self._proxy.roles + return ServiceContext(self._version, sid=sid) - @property - def users(self): + def __call__(self, sid: str) -> ServiceContext: """ - Access the users + Constructs a ServiceContext - :returns: twilio.rest.chat.v1.service.user.UserList - :rtype: twilio.rest.chat.v1.service.user.UserList + :param sid: """ - return self._proxy.users + return ServiceContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/ip_messaging/v1/service/channel/__init__.py b/twilio/rest/ip_messaging/v1/service/channel/__init__.py index 4be634df3e..14423c9e38 100644 --- a/twilio/rest/ip_messaging/v1/service/channel/__init__.py +++ b/twilio/rest/ip_messaging/v1/service/channel/__init__.py @@ -1,616 +1,790 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 ChannelList(ListResource): - """ """ +class ChannelInstance(InstanceResource): - def __init__(self, version, service_sid): - """ - Initialize the ChannelList + 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") - :param Version version: Version that contains the resource - :param service_sid: The service_sid + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ChannelContext] = None - :returns: twilio.rest.chat.v1.service.channel.ChannelList - :rtype: twilio.rest.chat.v1.service.channel.ChannelList + @property + def _proxy(self) -> "ChannelContext": """ - super(ChannelList, self).__init__(version) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Channels'.format(**self._solution) + :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 create(self, friendly_name=values.unset, unique_name=values.unset, - attributes=values.unset, type=values.unset): + def delete(self) -> bool: """ - Create a new ChannelInstance + Deletes the ChannelInstance - :param unicode friendly_name: The friendly_name - :param unicode unique_name: The unique_name - :param unicode attributes: The attributes - :param ChannelInstance.ChannelType type: The type - :returns: Newly created ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'FriendlyName': friendly_name, - 'UniqueName': unique_name, - 'Attributes': attributes, - 'Type': type, - }) + return self._proxy.delete() - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelInstance - return ChannelInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, type=values.unset, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + return await self._proxy.delete_async() - :param ChannelInstance.ChannelType type: The type - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.channel.ChannelInstance] + def fetch(self) -> "ChannelInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the ChannelInstance - page = self.page(type=type, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched ChannelInstance + """ + return self._proxy.fetch() - def list(self, type=values.unset, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the ChannelInstance - :param ChannelInstance.ChannelType type: The type - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.channel.ChannelInstance] + :returns: The fetched ChannelInstance """ - return list(self.stream(type=type, limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, type=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "ChannelInstance": """ - Retrieve a single page of ChannelInstance records from the API. - Request is executed immediately + Update the ChannelInstance - :param ChannelInstance.ChannelType type: The type - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :param friendly_name: + :param unique_name: + :param attributes: - :returns: Page of ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelPage + :returns: The updated ChannelInstance """ - params = values.of({ - 'Type': serialize.map(type, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + return self._proxy.update( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, ) - return ChannelPage(self._version, response, self._solution) - - def get_page(self, target_url): + 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": """ - Retrieve a specific page of ChannelInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the ChannelInstance - :param str target_url: API-generated URL for the requested results page + :param friendly_name: + :param unique_name: + :param attributes: - :returns: Page of ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelPage + :returns: The updated ChannelInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, ) - return ChannelPage(self._version, response, self._solution) - - def get(self, sid): + @property + def invites(self) -> InviteList: """ - Constructs a ChannelContext - - :param sid: The sid - - :returns: twilio.rest.chat.v1.service.channel.ChannelContext - :rtype: twilio.rest.chat.v1.service.channel.ChannelContext + Access the invites """ - return ChannelContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.invites - def __call__(self, sid): + @property + def members(self) -> MemberList: """ - Constructs a ChannelContext - - :param sid: The sid + Access the members + """ + return self._proxy.members - :returns: twilio.rest.chat.v1.service.channel.ChannelContext - :rtype: twilio.rest.chat.v1.service.channel.ChannelContext + @property + def messages(self) -> MessageList: """ - return ChannelContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Access the messages + """ + return self._proxy.messages - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ChannelPage(Page): - """ """ +class ChannelContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the ChannelPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid + Initialize the ChannelContext - :returns: twilio.rest.chat.v1.service.channel.ChannelPage - :rtype: twilio.rest.chat.v1.service.channel.ChannelPage + :param version: Version that contains the resource + :param service_sid: + :param sid: """ - super(ChannelPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Channels/{sid}".format(**self._solution) - def get_instance(self, payload): + self._invites: Optional[InviteList] = None + self._members: Optional[MemberList] = None + self._messages: Optional[MessageList] = None + + def delete(self) -> bool: """ - Build an instance of ChannelInstance + Deletes the ChannelInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v1.service.channel.ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance + :returns: True if delete succeeds, False otherwise """ - return ChannelInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the ChannelInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class ChannelContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, service_sid, sid): + def fetch(self) -> ChannelInstance: """ - Initialize the ChannelContext + Fetch the ChannelInstance - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: The sid - :returns: twilio.rest.chat.v1.service.channel.ChannelContext - :rtype: twilio.rest.chat.v1.service.channel.ChannelContext + :returns: The fetched ChannelInstance """ - super(ChannelContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Channels/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - # Dependents - self._members = None - self._messages = None - self._invites = None + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - def fetch(self): + async def fetch_async(self) -> ChannelInstance: """ - Fetch a ChannelInstance + Asynchronous coroutine to fetch the ChannelInstance + - :returns: Fetched ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance + :returns: The fetched ChannelInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + def update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ChannelInstance: """ - Deletes the ChannelInstance + Update the ChannelInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param friendly_name: + :param unique_name: + :param attributes: + + :returns: The updated ChannelInstance """ - return self._version.delete('delete', self._uri) - def update(self, friendly_name=values.unset, unique_name=values.unset, - attributes=values.unset): + 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: """ - Update the ChannelInstance + Asynchronous coroutine to update the ChannelInstance - :param unicode friendly_name: The friendly_name - :param unicode unique_name: The unique_name - :param unicode attributes: The attributes + :param friendly_name: + :param unique_name: + :param attributes: - :returns: Updated ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance + :returns: The updated ChannelInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'UniqueName': unique_name, - 'Attributes': attributes, - }) - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) @property - def members(self): + def invites(self) -> InviteList: """ - Access the members + Access the invites + """ + if self._invites is None: + self._invites = InviteList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._invites - :returns: twilio.rest.chat.v1.service.channel.member.MemberList - :rtype: twilio.rest.chat.v1.service.channel.member.MemberList + @property + def members(self) -> MemberList: + """ + Access the members """ if self._members is None: self._members = MemberList( self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) return self._members @property - def messages(self): + def messages(self) -> MessageList: """ Access the messages - - :returns: twilio.rest.chat.v1.service.channel.message.MessageList - :rtype: twilio.rest.chat.v1.service.channel.message.MessageList """ if self._messages is None: self._messages = MessageList( self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) return self._messages - @property - def invites(self): + def __repr__(self) -> str: """ - Access the invites + Provide a friendly representation - :returns: twilio.rest.chat.v1.service.channel.invite.InviteList - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteList + :returns: Machine friendly representation """ - if self._invites is None: - self._invites = InviteList( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['sid'], - ) - return self._invites + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" -class ChannelInstance(InstanceResource): - """ """ - - class ChannelType(object): - PUBLIC = "public" - PRIVATE = "private" +class ChannelList(ListResource): - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the ChannelInstance - - :returns: twilio.rest.chat.v1.service.channel.ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance - """ - super(ChannelInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'friendly_name': payload['friendly_name'], - 'unique_name': payload['unique_name'], - 'attributes': payload['attributes'], - 'type': payload['type'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'created_by': payload['created_by'], - 'members_count': deserialize.integer(payload['members_count']), - 'messages_count': deserialize.integer(payload['messages_count']), - 'url': payload['url'], - 'links': payload['links'], - } + def __init__(self, version: Version, service_sid: str): + """ + Initialize the ChannelList - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + :param version: Version that contains the resource + :param service_sid: - @property - def _proxy(self): """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + super().__init__(version) - :returns: ChannelContext for this ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelContext - """ - if self._context is None: - self._context = ChannelContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Channels".format(**self._solution) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + 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: """ - return self._properties['sid'] + Create the ChannelInstance - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + :param friendly_name: + :param unique_name: + :param attributes: + :param type: - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode + :returns: The created ChannelInstance """ - return self._properties['service_sid'] - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "Type": type, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def unique_name(self): - """ - :returns: The unique_name - :rtype: unicode - """ - return self._properties['unique_name'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def attributes(self): - """ - :returns: The attributes - :rtype: unicode - """ - return self._properties['attributes'] + headers["Accept"] = "application/json" - @property - def type(self): - """ - :returns: The type - :rtype: ChannelInstance.ChannelType - """ - return self._properties['type'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def date_updated(self): + 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: """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + Asynchronously create the ChannelInstance - @property - def created_by(self): - """ - :returns: The created_by - :rtype: unicode - """ - return self._properties['created_by'] + :param friendly_name: + :param unique_name: + :param attributes: + :param type: - @property - def members_count(self): + :returns: The created ChannelInstance """ - :returns: The members_count - :rtype: unicode - """ - return self._properties['members_count'] - @property - def messages_count(self): + 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]: """ - :returns: The messages_count - :rtype: unicode + 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 """ - return self._properties['messages_count'] + limits = self._version.read_limits(limit, page_size) + page = self.page(type=type, page_size=limits["page_size"]) - @property - def url(self): + 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]: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(type=type, page_size=limits["page_size"]) - @property - def links(self): + 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]: """ - :returns: The links - :rtype: unicode + 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]: """ - return self._properties['links'] + 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 fetch(self): + 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: """ - Fetch a ChannelInstance + Retrieve a single page of ChannelInstance records from the API. + Request is executed immediately - :returns: Fetched ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance + :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 """ - return self._proxy.fetch() + 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"}) - def delete(self): + 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: """ - Deletes the ChannelInstance + Asynchronously retrieve a single page of ChannelInstance records from the API. + Request is executed immediately - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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 """ - return self._proxy.delete() + 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" - def update(self, friendly_name=values.unset, unique_name=values.unset, - attributes=values.unset): + 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: """ - Update the ChannelInstance + Retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately - :param unicode friendly_name: The friendly_name - :param unicode unique_name: The unique_name - :param unicode attributes: The attributes + :param target_url: API-generated URL for the requested results page - :returns: Updated ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance + :returns: Page of ChannelInstance """ - return self._proxy.update( - friendly_name=friendly_name, - unique_name=unique_name, - attributes=attributes, - ) + response = self._version.domain.twilio.request("GET", target_url) + return ChannelPage(self._version, response, self._solution) - @property - def members(self): + async def get_page_async(self, target_url: str) -> ChannelPage: """ - Access the members + Asynchronously retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately - :returns: twilio.rest.chat.v1.service.channel.member.MemberList - :rtype: twilio.rest.chat.v1.service.channel.member.MemberList + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance """ - return self._proxy.members + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelPage(self._version, response, self._solution) - @property - def messages(self): + def get(self, sid: str) -> ChannelContext: """ - Access the messages + Constructs a ChannelContext - :returns: twilio.rest.chat.v1.service.channel.message.MessageList - :rtype: twilio.rest.chat.v1.service.channel.message.MessageList + :param sid: """ - return self._proxy.messages + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - @property - def invites(self): + def __call__(self, sid: str) -> ChannelContext: """ - Access the invites + Constructs a ChannelContext - :returns: twilio.rest.chat.v1.service.channel.invite.InviteList - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteList + :param sid: """ - return self._proxy.invites + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/ip_messaging/v1/service/channel/invite.py b/twilio/rest/ip_messaging/v1/service/channel/invite.py index 3f6e695ffd..d348540346 100644 --- a/twilio/rest/ip_messaging/v1/service/channel/invite.py +++ b/twilio/rest/ip_messaging/v1/service/channel/invite.py @@ -1,462 +1,598 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 InviteList(ListResource): - """ """ +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 - def __init__(self, version, service_sid, channel_sid): + @property + def _proxy(self) -> "InviteContext": """ - Initialize the InviteList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param channel_sid: The channel_sid + :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 - :returns: twilio.rest.chat.v1.service.channel.invite.InviteList - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteList + def delete(self) -> bool: """ - super(InviteList, self).__init__(version) + Deletes the InviteInstance - # 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, role_sid=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create a new InviteInstance - - :param unicode identity: The identity - :param unicode role_sid: The role_sid + return self._proxy.delete() - :returns: Newly created InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteInstance + async def delete_async(self) -> bool: """ - data = values.of({'Identity': identity, 'RoleSid': role_sid, }) + Asynchronous coroutine that deletes the InviteInstance - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - return InviteInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - ) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def stream(self, identity=values.unset, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the InviteInstance - :param unicode identity: The identity - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.channel.invite.InviteInstance] + :returns: The fetched InviteInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(identity=identity, page_size=limits['page_size'], ) + async def fetch_async(self) -> "InviteInstance": + """ + Asynchronous coroutine to fetch the InviteInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, identity=values.unset, limit=None, page_size=None): + :returns: The fetched 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 unicode identity: The identity - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + return await self._proxy.fetch_async() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.channel.invite.InviteInstance] + def __repr__(self) -> str: """ - return list(self.stream(identity=identity, limit=limit, page_size=page_size, )) + Provide a friendly representation - def page(self, identity=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + :returns: Machine friendly representation """ - Retrieve a single page of InviteInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param unicode identity: The identity - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InvitePage +class InviteContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ - params = values.of({ - 'Identity': serialize.map(identity, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Initialize the InviteContext - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + :param sid: + """ + super().__init__(version) - return InvitePage(self._version, response, self._solution) + # 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 get_page(self, target_url): + def delete(self) -> bool: """ - Retrieve a specific page of InviteInstance records from the API. - Request is executed immediately + Deletes the InviteInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InvitePage + :returns: True if delete succeeds, False otherwise """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return InvitePage(self._version, response, self._solution) + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def get(self, sid): + async def delete_async(self) -> bool: """ - Constructs a InviteContext + Asynchronous coroutine that deletes the InviteInstance - :param sid: The sid - :returns: twilio.rest.chat.v1.service.channel.invite.InviteContext - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteContext + :returns: True if delete succeeds, False otherwise """ - return InviteContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers ) - def __call__(self, sid): + def fetch(self) -> InviteInstance: """ - Constructs a InviteContext + Fetch the InviteInstance - :param sid: The sid - :returns: twilio.rest.chat.v1.service.channel.invite.InviteContext - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteContext + :returns: The fetched InviteInstance """ - return InviteContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InviteInstance( self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + async def fetch_async(self) -> InviteInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the InviteInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched InviteInstance """ - return '' + headers = values.of({}) -class InvitePage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): - """ - Initialize the InvitePage + 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"], + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :param channel_sid: The channel_sid + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.chat.v1.service.channel.invite.InvitePage - :rtype: twilio.rest.chat.v1.service.channel.invite.InvitePage + :returns: Machine friendly representation """ - super(InvitePage, self).__init__(version, response) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Path Solution - self._solution = solution - def get_instance(self, payload): +class InvitePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: """ Build an instance of InviteInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.chat.v1.service.channel.invite.InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.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'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class InviteContext(InstanceContext): - """ """ +class InviteList(ListResource): - def __init__(self, version, service_sid, channel_sid, sid): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ - Initialize the InviteContext + Initialize the InviteList - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param channel_sid: The channel_sid - :param sid: The sid + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: - :returns: twilio.rest.chat.v1.service.channel.invite.InviteContext - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteContext """ - super(InviteContext, self).__init__(version) + 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) + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Invites".format( + **self._solution + ) - def fetch(self): + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: """ - Fetch a InviteInstance + Create the InviteInstance + + :param identity: + :param role_sid: - :returns: Fetched InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteInstance + :returns: The created InviteInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def delete(self): + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: """ - Deletes the InviteInstance + Asynchronously create the InviteInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :param identity: + :param role_sid: - def __repr__(self): + :returns: The created InviteInstance """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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" -class InviteInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - def __init__(self, version, payload, service_sid, channel_sid, sid=None): + 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]: """ - Initialize the 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: twilio.rest.chat.v1.service.channel.invite.InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteInstance + :returns: Generator that will yield up to limit results """ - super(InviteInstance, self).__init__(version) + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'channel_sid': payload['channel_sid'], - 'service_sid': payload['service_sid'], - 'identity': payload['identity'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'role_sid': payload['role_sid'], - 'created_by': payload['created_by'], - 'url': payload['url'], - } + return self._version.stream(page, limits["limit"]) - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], - } + 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. - @property - def _proxy(self): + :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 """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) - :returns: InviteContext for this InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteContext + 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]: """ - 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'], + 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, ) - return self._context + ) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: """ - return self._properties['sid'] + 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. - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + :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, + ) + ] - @property - def channel_sid(self): - """ - :returns: The channel_sid - :rtype: unicode + 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: """ - return self._properties['channel_sid'] + Retrieve a single page of InviteInstance records from the API. + Request is executed immediately - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] + :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 - @property - def identity(self): - """ - :returns: The identity - :rtype: unicode + :returns: Page of InviteInstance """ - return self._properties['identity'] + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Accept"] = "application/json" - @property - def role_sid(self): + 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: """ - :returns: The role_sid - :rtype: unicode + 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 """ - return self._properties['role_sid'] + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def created_by(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The created_by - :rtype: unicode + 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 """ - return self._properties['created_by'] + response = self._version.domain.twilio.request("GET", target_url) + return InvitePage(self._version, response, self._solution) - @property - def url(self): + async def get_page_async(self, target_url: str) -> InvitePage: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return InvitePage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> InviteContext: """ - Fetch a InviteInstance + Constructs a InviteContext - :returns: Fetched InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteInstance + :param sid: """ - return self._proxy.fetch() + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - def delete(self): + def __call__(self, sid: str) -> InviteContext: """ - Deletes the InviteInstance + Constructs a InviteContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: """ - return self._proxy.delete() + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/ip_messaging/v1/service/channel/member.py b/twilio/rest/ip_messaging/v1/service/channel/member.py index a2cfe54f28..26a68650ef 100644 --- a/twilio/rest/ip_messaging/v1/service/channel/member.py +++ b/twilio/rest/ip_messaging/v1/service/channel/member.py @@ -1,514 +1,716 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 MemberList(ListResource): - """ """ +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 - def __init__(self, version, service_sid, channel_sid): + @property + def _proxy(self) -> "MemberContext": """ - Initialize the MemberList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param channel_sid: The channel_sid + :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 - :returns: twilio.rest.chat.v1.service.channel.member.MemberList - :rtype: twilio.rest.chat.v1.service.channel.member.MemberList + def delete(self) -> bool: """ - super(MemberList, self).__init__(version) + Deletes the MemberInstance - # 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, role_sid=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create a new MemberInstance + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MemberInstance - :param unicode identity: The identity - :param unicode role_sid: The role_sid - :returns: Newly created MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({'Identity': identity, 'RoleSid': role_sid, }) + return await self._proxy.delete_async() - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + def fetch(self) -> "MemberInstance": + """ + Fetch the MemberInstance - return MemberInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - ) - def stream(self, identity=values.unset, limit=None, page_size=None): + :returns: The fetched 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. + return self._proxy.fetch() - :param unicode identity: The identity - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + async def fetch_async(self) -> "MemberInstance": + """ + Asynchronous coroutine to fetch the MemberInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.channel.member.MemberInstance] + + :returns: The fetched MemberInstance """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.fetch_async() - page = self.page(identity=identity, page_size=limits['page_size'], ) + def update( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> "MemberInstance": + """ + Update the MemberInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) + :param role_sid: + :param last_consumed_message_index: - def list(self, identity=values.unset, limit=None, page_size=None): + :returns: The updated 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. + return self._proxy.update( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + ) - :param unicode identity: The identity - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + 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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.channel.member.MemberInstance] + :param role_sid: + :param last_consumed_message_index: + + :returns: The updated MemberInstance """ - return list(self.stream(identity=identity, limit=limit, page_size=page_size, )) + return await self._proxy.update_async( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + ) - def page(self, identity=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def __repr__(self) -> str: """ - Retrieve a single page of MemberInstance records from the API. - Request is executed immediately + Provide a friendly representation - :param unicode identity: The identity - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: Page of MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberPage + +class MemberContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ - params = values.of({ - 'Identity': serialize.map(identity, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Initialize the MemberContext - response = self._version.page( - 'GET', - self._uri, - params=params, + :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 + ) ) - return MemberPage(self._version, response, self._solution) + def delete(self) -> bool: + """ + Deletes the MemberInstance - def get_page(self, target_url): + + :returns: True if delete succeeds, False otherwise """ - Retrieve a specific page of MemberInstance records from the API. - Request is executed immediately - :param str target_url: API-generated URL for the requested results page + headers = values.of({}) - :returns: Page of MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberPage + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Asynchronous coroutine that deletes the MemberInstance - return MemberPage(self._version, response, self._solution) - def get(self, sid): + :returns: True if delete succeeds, False otherwise """ - Constructs a MemberContext - :param sid: The sid + headers = values.of({}) - :returns: twilio.rest.chat.v1.service.channel.member.MemberContext - :rtype: twilio.rest.chat.v1.service.channel.member.MemberContext + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MemberInstance: """ - return MemberContext( + 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, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - def __call__(self, sid): + async def fetch_async(self) -> MemberInstance: """ - Constructs a MemberContext + Asynchronous coroutine to fetch the MemberInstance - :param sid: The sid - :returns: twilio.rest.chat.v1.service.channel.member.MemberContext - :rtype: twilio.rest.chat.v1.service.channel.member.MemberContext + :returns: The fetched MemberInstance """ - return MemberContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MemberInstance( self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + def update( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> MemberInstance: """ - Provide a friendly representation + Update the MemberInstance - :returns: Machine friendly representation - :rtype: str + :param role_sid: + :param last_consumed_message_index: + + :returns: The updated MemberInstance """ - return '' + data = values.of( + { + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" -class MemberPage(Page): - """ """ + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) - def __init__(self, version, response, solution): + 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: """ - Initialize the MemberPage + Asynchronous coroutine to update the MemberInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :param channel_sid: The channel_sid + :param role_sid: + :param last_consumed_message_index: - :returns: twilio.rest.chat.v1.service.channel.member.MemberPage - :rtype: twilio.rest.chat.v1.service.channel.member.MemberPage + :returns: The updated MemberInstance """ - super(MemberPage, self).__init__(version, response) - # Path Solution - self._solution = solution + 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 get_instance(self, payload): + def __repr__(self) -> str: """ - Build an instance of MemberInstance + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v1.service.channel.member.MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance +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'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class MemberContext(InstanceContext): - """ """ +class MemberList(ListResource): - def __init__(self, version, service_sid, channel_sid, sid): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ - Initialize the MemberContext + Initialize the MemberList - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param channel_sid: The channel_sid - :param sid: The sid + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: - :returns: twilio.rest.chat.v1.service.channel.member.MemberContext - :rtype: twilio.rest.chat.v1.service.channel.member.MemberContext """ - super(MemberContext, self).__init__(version) + 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) + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Members".format( + **self._solution + ) - def fetch(self): + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> MemberInstance: """ - Fetch a MemberInstance + Create the MemberInstance - :returns: Fetched MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance + :param identity: + :param role_sid: + + :returns: The created MemberInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def delete(self): + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> MemberInstance: """ - Deletes the MemberInstance + Asynchronously create the MemberInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :param identity: + :param role_sid: - def update(self, role_sid=values.unset, - last_consumed_message_index=values.unset): + :returns: The created MemberInstance """ - Update the MemberInstance - :param unicode role_sid: The role_sid - :param unicode last_consumed_message_index: The last_consumed_message_index + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: Updated MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance - """ - data = values.of({'RoleSid': role_sid, 'LastConsumedMessageIndex': last_consumed_message_index, }) + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def __repr__(self): + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MemberInstance]: """ - Provide a friendly representation + 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. - :returns: Machine friendly representation - :rtype: str + :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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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"]) -class MemberInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, service_sid, channel_sid, sid=None): - """ - Initialize the MemberInstance - - :returns: twilio.rest.chat.v1.service.channel.member.MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance - """ - super(MemberInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'channel_sid': payload['channel_sid'], - 'service_sid': payload['service_sid'], - 'identity': payload['identity'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'role_sid': payload['role_sid'], - 'last_consumed_message_index': deserialize.integer(payload['last_consumed_message_index']), - 'last_consumption_timestamp': deserialize.iso8601_datetime(payload['last_consumption_timestamp']), - 'url': payload['url'], - } + 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. - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], - } + :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) - @property - def _proxy(self): + :returns: Generator that will yield up to limit results """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) - :returns: MemberContext for this MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberContext + 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]: """ - 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'], + 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, ) - return self._context + ) - @property - def sid(self): + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + 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. - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + :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, + ) + ] - @property - def channel_sid(self): - """ - :returns: The channel_sid - :rtype: unicode + 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: """ - return self._properties['channel_sid'] + Retrieve a single page of MemberInstance records from the API. + Request is executed immediately - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] + :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 - @property - def identity(self): - """ - :returns: The identity - :rtype: unicode + :returns: Page of MemberInstance """ - return self._properties['identity'] + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Accept"] = "application/json" - @property - def role_sid(self): - """ - :returns: The role_sid - :rtype: unicode - """ - return self._properties['role_sid'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, self._solution) - @property - def last_consumed_message_index(self): - """ - :returns: The last_consumed_message_index - :rtype: unicode + 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: """ - return self._properties['last_consumed_message_index'] + Asynchronously retrieve a single page of MemberInstance records from the API. + Request is executed immediately - @property - def last_consumption_timestamp(self): - """ - :returns: The last_consumption_timestamp - :rtype: datetime - """ - return self._properties['last_consumption_timestamp'] + :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 - @property - def url(self): + :returns: Page of MemberInstance """ - :returns: The url - :rtype: unicode + 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: """ - return self._properties['url'] + Retrieve a specific page of MemberInstance records from the API. + Request is executed immediately - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance """ - Fetch a MemberInstance + response = self._version.domain.twilio.request("GET", target_url) + return MemberPage(self._version, response, self._solution) - :returns: Fetched MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance + async def get_page_async(self, target_url: str) -> MemberPage: """ - return self._proxy.fetch() + 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 - def delete(self): + :returns: Page of MemberInstance """ - Deletes the MemberInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return MemberPage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def get(self, sid: str) -> MemberContext: """ - return self._proxy.delete() + Constructs a MemberContext - def update(self, role_sid=values.unset, - last_consumed_message_index=values.unset): + :param sid: """ - Update the MemberInstance + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - :param unicode role_sid: The role_sid - :param unicode last_consumed_message_index: The last_consumed_message_index + def __call__(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext - :returns: Updated MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance + :param sid: """ - return self._proxy.update( - role_sid=role_sid, - last_consumed_message_index=last_consumed_message_index, + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/ip_messaging/v1/service/channel/message.py b/twilio/rest/ip_messaging/v1/service/channel/message.py index cf450afa13..ad7c05d8a1 100644 --- a/twilio/rest/ip_messaging/v1/service/channel/message.py +++ b/twilio/rest/ip_messaging/v1/service/channel/message.py @@ -1,531 +1,731 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 MessageList(ListResource): - """ """ +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") - def __init__(self, version, service_sid, channel_sid): + 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": """ - Initialize the MessageList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param channel_sid: The channel_sid + :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 - :returns: twilio.rest.chat.v1.service.channel.message.MessageList - :rtype: twilio.rest.chat.v1.service.channel.message.MessageList + def delete(self) -> bool: """ - super(MessageList, self).__init__(version) + Deletes the MessageInstance - # 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, from_=values.unset, attributes=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create a new MessageInstance + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance - :param unicode body: The body - :param unicode from_: The from - :param unicode attributes: The attributes - :returns: Newly created MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({'Body': body, 'From': from_, 'Attributes': attributes, }) + return await self._proxy.delete_async() - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + def fetch(self) -> "MessageInstance": + """ + Fetch the MessageInstance - return MessageInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - ) - def stream(self, order=values.unset, limit=None, page_size=None): + :returns: The fetched 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. + return self._proxy.fetch() - :param MessageInstance.OrderType order: The order - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + async def fetch_async(self) -> "MessageInstance": + """ + Asynchronous coroutine to fetch the MessageInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.channel.message.MessageInstance] + + :returns: The fetched MessageInstance """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.fetch_async() - page = self.page(order=order, page_size=limits['page_size'], ) + def update( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Update the MessageInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) + :param body: + :param attributes: - def list(self, order=values.unset, limit=None, page_size=None): + :returns: The updated 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. + return self._proxy.update( + body=body, + attributes=attributes, + ) - :param MessageInstance.OrderType order: The order - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + async def update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Asynchronous coroutine to update the MessageInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.channel.message.MessageInstance] + :param body: + :param attributes: + + :returns: The updated MessageInstance """ - return list(self.stream(order=order, limit=limit, page_size=page_size, )) + return await self._proxy.update_async( + body=body, + attributes=attributes, + ) - def page(self, order=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def __repr__(self) -> str: """ - Retrieve a single page of MessageInstance records from the API. - Request is executed immediately + Provide a friendly representation - :param MessageInstance.OrderType order: The order - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: Page of MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessagePage + +class MessageContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ - params = values.of({ - 'Order': order, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Initialize the MessageContext - response = self._version.page( - 'GET', - self._uri, - params=params, + :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 + ) ) - return MessagePage(self._version, response, self._solution) + def delete(self) -> bool: + """ + Deletes the MessageInstance - def get_page(self, target_url): + + :returns: True if delete succeeds, False otherwise """ - Retrieve a specific page of MessageInstance records from the API. - Request is executed immediately - :param str target_url: API-generated URL for the requested results page + headers = values.of({}) - :returns: Page of MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessagePage + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Asynchronous coroutine that deletes the MessageInstance - return MessagePage(self._version, response, self._solution) - def get(self, sid): + :returns: True if delete succeeds, False otherwise """ - Constructs a MessageContext - :param sid: The sid + headers = values.of({}) - :returns: twilio.rest.chat.v1.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v1.service.channel.message.MessageContext + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: """ - return MessageContext( + 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, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - def __call__(self, sid): + async def fetch_async(self) -> MessageInstance: """ - Constructs a MessageContext + Asynchronous coroutine to fetch the MessageInstance - :param sid: The sid - :returns: twilio.rest.chat.v1.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v1.service.channel.message.MessageContext + :returns: The fetched MessageInstance """ - return MessageContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MessageInstance( self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + def update( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: """ - Provide a friendly representation + Update the MessageInstance - :returns: Machine friendly representation - :rtype: str + :param body: + :param attributes: + + :returns: The updated MessageInstance """ - return '' + data = values.of( + { + "Body": body, + "Attributes": attributes, + } + ) + headers = values.of({}) -class MessagePage(Page): - """ """ + 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"], + ) - def __init__(self, version, response, solution): + async def update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: """ - Initialize the MessagePage + Asynchronous coroutine to update the MessageInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :param channel_sid: The channel_sid + :param body: + :param attributes: - :returns: twilio.rest.chat.v1.service.channel.message.MessagePage - :rtype: twilio.rest.chat.v1.service.channel.message.MessagePage + :returns: The updated MessageInstance """ - super(MessagePage, self).__init__(version, response) - # Path Solution - self._solution = solution + 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 + ) - def get_instance(self, payload): + 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: """ - Build an instance of MessageInstance + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v1.service.channel.message.MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance +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'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class MessageContext(InstanceContext): - """ """ +class MessageList(ListResource): - def __init__(self, version, service_sid, channel_sid, sid): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ - Initialize the MessageContext + Initialize the MessageList - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param channel_sid: The channel_sid - :param sid: The sid + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: - :returns: twilio.rest.chat.v1.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v1.service.channel.message.MessageContext """ - super(MessageContext, self).__init__(version) + 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) + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Messages".format( + **self._solution + ) - def fetch(self): + def create( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: """ - Fetch a MessageInstance + Create the MessageInstance - :returns: Fetched MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance + :param body: + :param from_: + :param attributes: + + :returns: The created MessageInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def delete(self): + async def create_async( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: """ - Deletes the MessageInstance + Asynchronously create the MessageInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :param body: + :param from_: + :param attributes: - def update(self, body=values.unset, attributes=values.unset): + :returns: The created MessageInstance """ - Update the MessageInstance - :param unicode body: The body - :param unicode attributes: The attributes + data = values.of( + { + "Body": body, + "From": from_, + "Attributes": attributes, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: Updated MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance - """ - data = values.of({'Body': body, 'Attributes': attributes, }) + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def __repr__(self): + def stream( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: """ - Provide a friendly representation + 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. - :returns: Machine friendly representation - :rtype: str + :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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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"]) -class MessageInstance(InstanceResource): - """ """ + 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. - class OrderType(object): - ASC = "asc" - DESC = "desc" + :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) - def __init__(self, version, payload, service_sid, channel_sid, sid=None): - """ - Initialize the MessageInstance - - :returns: twilio.rest.chat.v1.service.channel.message.MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance - """ - super(MessageInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'attributes': payload['attributes'], - 'service_sid': payload['service_sid'], - 'to': payload['to'], - 'channel_sid': payload['channel_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'was_edited': payload['was_edited'], - 'from_': payload['from'], - 'body': payload['body'], - 'index': deserialize.integer(payload['index']), - 'url': payload['url'], - } + :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"]) - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], - } + return self._version.stream_async(page, limits["limit"]) - @property - def _proxy(self): + def list( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: MessageContext for this MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageContext - """ - 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'], + :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, ) - return self._context + ) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + async def list_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: """ - return self._properties['sid'] + 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. - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + :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, + ) + ] - @property - def attributes(self): + 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: """ - :returns: The attributes - :rtype: unicode - """ - return self._properties['attributes'] + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] + :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 - @property - def to(self): - """ - :returns: The to - :rtype: unicode + :returns: Page of MessageInstance """ - return self._properties['to'] + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def channel_sid(self): - """ - :returns: The channel_sid - :rtype: unicode - """ - return self._properties['channel_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + headers["Accept"] = "application/json" - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) - @property - def was_edited(self): - """ - :returns: The was_edited - :rtype: bool + 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: """ - return self._properties['was_edited'] + Asynchronously retrieve a single page of MessageInstance records from the API. + Request is executed immediately - @property - def from_(self): - """ - :returns: The from - :rtype: unicode - """ - return self._properties['from_'] + :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 - @property - def body(self): - """ - :returns: The body - :rtype: unicode + :returns: Page of MessageInstance """ - return self._properties['body'] + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def index(self): - """ - :returns: The index - :rtype: unicode - """ - return self._properties['index'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def url(self): - """ - :returns: The url - :rtype: unicode + 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: """ - return self._properties['url'] + Retrieve a specific page of MessageInstance records from the API. + Request is executed immediately - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance """ - Fetch a MessageInstance + response = self._version.domain.twilio.request("GET", target_url) + return MessagePage(self._version, response, self._solution) - :returns: Fetched MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance + async def get_page_async(self, target_url: str) -> MessagePage: """ - return self._proxy.fetch() + 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 - def delete(self): + :returns: Page of MessageInstance """ - Deletes the MessageInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagePage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def get(self, sid: str) -> MessageContext: """ - return self._proxy.delete() + Constructs a MessageContext - def update(self, body=values.unset, attributes=values.unset): + :param sid: """ - Update the MessageInstance + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - :param unicode body: The body - :param unicode attributes: The attributes + def __call__(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext - :returns: Updated MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance + :param sid: """ - return self._proxy.update(body=body, attributes=attributes, ) + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/ip_messaging/v1/service/role.py b/twilio/rest/ip_messaging/v1/service/role.py index ff62493a22..d5d0628032 100644 --- a/twilio/rest/ip_messaging/v1/service/role.py +++ b/twilio/rest/ip_messaging/v1/service/role.py @@ -1,460 +1,645 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 RoleList(ListResource): - """ """ +class RoleInstance(InstanceResource): - def __init__(self, version, service_sid): - """ - Initialize the RoleList + class RoleType(object): + CHANNEL = "channel" + DEPLOYMENT = "deployment" - :param Version version: Version that contains the resource - :param service_sid: The service_sid + """ + :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 - :returns: twilio.rest.chat.v1.service.role.RoleList - :rtype: twilio.rest.chat.v1.service.role.RoleList + @property + def _proxy(self) -> "RoleContext": """ - super(RoleList, self).__init__(version) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Roles'.format(**self._solution) + :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 create(self, friendly_name, type, permission): + def delete(self) -> bool: """ - Create a new RoleInstance + Deletes the RoleInstance - :param unicode friendly_name: The friendly_name - :param RoleInstance.RoleType type: The type - :param unicode permission: The permission - :returns: Newly created RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Type': type, - 'Permission': serialize.map(permission, lambda e: e), - }) + return self._proxy.delete() - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance - return RoleInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return await self._proxy.delete_async() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.role.RoleInstance] + def fetch(self) -> "RoleInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the RoleInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched RoleInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the RoleInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.role.RoleInstance] + :returns: The fetched RoleInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def update(self, permission: List[str]) -> "RoleInstance": """ - Retrieve a single page of RoleInstance records from the API. - Request is executed immediately + Update the RoleInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :param permission: - :returns: Page of RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RolePage + :returns: The updated RoleInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + return self._proxy.update( + permission=permission, ) - return RolePage(self._version, response, self._solution) - - def get_page(self, target_url): + async def update_async(self, permission: List[str]) -> "RoleInstance": """ - Retrieve a specific page of RoleInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the RoleInstance - :param str target_url: API-generated URL for the requested results page + :param permission: - :returns: Page of RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RolePage + :returns: The updated RoleInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + permission=permission, ) - return RolePage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a RoleContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - :param sid: The sid +class RoleContext(InstanceContext): - :returns: twilio.rest.chat.v1.service.role.RoleContext - :rtype: twilio.rest.chat.v1.service.role.RoleContext + def __init__(self, version: Version, service_sid: str, sid: str): """ - return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Initialize the RoleContext - def __call__(self, sid): + :param version: Version that contains the resource + :param service_sid: + :param sid: """ - Constructs a RoleContext + super().__init__(version) - :param sid: The sid + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Roles/{sid}".format(**self._solution) - :returns: twilio.rest.chat.v1.service.role.RoleContext - :rtype: twilio.rest.chat.v1.service.role.RoleContext + def delete(self) -> bool: """ - return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Deletes the RoleInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class RolePage(Page): - """ """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, response, solution): + async def delete_async(self) -> bool: """ - Initialize the RolePage + Asynchronous coroutine that deletes the RoleInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :returns: twilio.rest.chat.v1.service.role.RolePage - :rtype: twilio.rest.chat.v1.service.role.RolePage + :returns: True if delete succeeds, False otherwise """ - super(RolePage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: """ - Build an instance of RoleInstance + Fetch the RoleInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v1.service.role.RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance + :returns: The fetched RoleInstance """ - return RoleInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def __repr__(self): - """ - Provide a friendly representation + headers = values.of({}) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Accept"] = "application/json" + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) -class RoleContext(InstanceContext): - """ """ + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - def __init__(self, version, service_sid, sid): + async def fetch_async(self) -> RoleInstance: """ - Initialize the RoleContext + Asynchronous coroutine to fetch the RoleInstance - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: The sid - :returns: twilio.rest.chat.v1.service.role.RoleContext - :rtype: twilio.rest.chat.v1.service.role.RoleContext + :returns: The fetched RoleInstance """ - super(RoleContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Roles/{sid}'.format(**self._solution) + 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 fetch(self): + def update(self, permission: List[str]) -> RoleInstance: """ - Fetch a RoleInstance + Update the RoleInstance + + :param permission: - :returns: Fetched RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance + :returns: The updated RoleInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def update_async(self, permission: List[str]) -> RoleInstance: """ - Deletes the RoleInstance + Asynchronous coroutine to update the RoleInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :param permission: - def update(self, permission): + :returns: The updated RoleInstance """ - Update the RoleInstance - :param unicode permission: The permission + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) - :returns: Updated RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance - """ - data = values.of({'Permission': serialize.map(permission, lambda e: e), }) + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class RoleInstance(InstanceResource): - """ """ +class RolePage(Page): - class RoleType(object): - CHANNEL = "channel" - DEPLOYMENT = "deployment" + def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: + """ + Build an instance of RoleInstance - def __init__(self, version, payload, service_sid, sid=None): + :param payload: Payload response from the API """ - Initialize the RoleInstance + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - :returns: twilio.rest.chat.v1.service.role.RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance + def __repr__(self) -> str: """ - super(RoleInstance, self).__init__(version) + Provide a friendly representation - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'friendly_name': payload['friendly_name'], - 'type': payload['type'], - 'permissions': payload['permissions'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - } + :returns: Machine friendly representation + """ + return "" - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context +class RoleList(ListResource): - :returns: RoleContext for this RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleContext + def __init__(self, version: Version, service_sid: str): """ - if self._context is None: - self._context = RoleContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + Initialize the RoleList + + :param version: Version that contains the resource + :param service_sid: - @property - def sid(self): """ - :returns: The sid - :rtype: unicode + 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: """ - return self._properties['sid'] + Create the RoleInstance - @property - def account_sid(self): + :param friendly_name: + :param type: + :param permission: + + :returns: The created RoleInstance """ - :returns: The account_sid - :rtype: unicode + + 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: """ - return self._properties['account_sid'] + Asynchronously create the RoleInstance - @property - def service_sid(self): + :param friendly_name: + :param type: + :param permission: + + :returns: The created RoleInstance """ - :returns: The service_sid - :rtype: unicode + + 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]: """ - return self._properties['service_sid'] + 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. - @property - def friendly_name(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The friendly_name - :rtype: unicode + 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]: """ - return self._properties['friendly_name'] + 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. - @property - def type(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The type - :rtype: RoleInstance.RoleType + 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]: """ - return self._properties['type'] + Lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def permissions(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The permissions - :rtype: unicode + 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]: """ - return self._properties['permissions'] + 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. - @property - def date_created(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The date_created - :rtype: datetime + 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: """ - return self._properties['date_created'] + Retrieve a single page of RoleInstance records from the API. + Request is executed immediately - @property - def date_updated(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The date_updated - :rtype: datetime + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page of RoleInstance records from the API. + Request is executed immediately - @property - def url(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The url - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of RoleInstance """ - Fetch a RoleInstance + response = self._version.domain.twilio.request("GET", target_url) + return RolePage(self._version, response, self._solution) - :returns: Fetched RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance + async def get_page_async(self, target_url: str) -> RolePage: """ - return self._proxy.fetch() + 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 - def delete(self): + :returns: Page of RoleInstance """ - Deletes the RoleInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return RolePage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def get(self, sid: str) -> RoleContext: """ - return self._proxy.delete() + Constructs a RoleContext - def update(self, permission): + :param sid: """ - Update the RoleInstance + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - :param unicode permission: The permission + def __call__(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext - :returns: Updated RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance + :param sid: """ - return self._proxy.update(permission, ) + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/ip_messaging/v1/service/user/__init__.py b/twilio/rest/ip_messaging/v1/service/user/__init__.py index 01e1a45c0c..5f37f2d3aa 100644 --- a/twilio/rest/ip_messaging/v1/service/user/__init__.py +++ b/twilio/rest/ip_messaging/v1/service/user/__init__.py @@ -1,539 +1,723 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 UserList(ListResource): - """ """ - - def __init__(self, version, service_sid): - """ - Initialize the UserList +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") - :param Version version: Version that contains the resource - :param service_sid: The service_sid + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[UserContext] = None - :returns: twilio.rest.chat.v1.service.user.UserList - :rtype: twilio.rest.chat.v1.service.user.UserList + @property + def _proxy(self) -> "UserContext": """ - super(UserList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Users'.format(**self._solution) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def create(self, identity, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset): + :returns: UserContext for this UserInstance """ - Create a new UserInstance - - :param unicode identity: The identity - :param unicode role_sid: The role_sid - :param unicode attributes: The attributes - :param unicode friendly_name: The friendly_name + if self._context is None: + self._context = UserContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: Newly created UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance + def delete(self) -> bool: """ - data = values.of({ - 'Identity': identity, - 'RoleSid': role_sid, - 'Attributes': attributes, - 'FriendlyName': friendly_name, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + Deletes the UserInstance - return UserInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.user.UserInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the UserInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the UserInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.user.UserInstance] + :returns: The fetched UserInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_async(self) -> "UserInstance": """ - Retrieve a single page of UserInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the UserInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserPage + :returns: The fetched UserInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return UserPage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def get_page(self, target_url): + def update( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": """ - Retrieve a specific page of UserInstance records from the API. - Request is executed immediately + Update the UserInstance - :param str target_url: API-generated URL for the requested results page + :param role_sid: + :param attributes: + :param friendly_name: - :returns: Page of UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserPage + :returns: The updated UserInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, ) - return UserPage(self._version, response, self._solution) - - def get(self, 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": """ - Constructs a UserContext + Asynchronous coroutine to update the UserInstance - :param sid: The sid + :param role_sid: + :param attributes: + :param friendly_name: - :returns: twilio.rest.chat.v1.service.user.UserContext - :rtype: twilio.rest.chat.v1.service.user.UserContext + :returns: The updated UserInstance """ - return UserContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_async( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) - def __call__(self, sid): + @property + def user_channels(self) -> UserChannelList: """ - Constructs a UserContext - - :param sid: The sid - - :returns: twilio.rest.chat.v1.service.user.UserContext - :rtype: twilio.rest.chat.v1.service.user.UserContext + Access the user_channels """ - return UserContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.user_channels - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class UserPage(Page): - """ """ +class UserContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the UserPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid + Initialize the UserContext - :returns: twilio.rest.chat.v1.service.user.UserPage - :rtype: twilio.rest.chat.v1.service.user.UserPage + :param version: Version that contains the resource + :param service_sid: + :param sid: """ - super(UserPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Users/{sid}".format(**self._solution) - def get_instance(self, payload): + self._user_channels: Optional[UserChannelList] = None + + def delete(self) -> bool: """ - Build an instance of UserInstance + Deletes the UserInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v1.service.user.UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance + :returns: True if delete succeeds, False otherwise """ - return UserInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the UserInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class UserContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, service_sid, sid): + def fetch(self) -> UserInstance: """ - Initialize the UserContext + Fetch the UserInstance - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: The sid - :returns: twilio.rest.chat.v1.service.user.UserContext - :rtype: twilio.rest.chat.v1.service.user.UserContext + :returns: The fetched UserInstance """ - super(UserContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Users/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - # Dependents - self._user_channels = None + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - def fetch(self): + async def fetch_async(self) -> UserInstance: """ - Fetch a UserInstance + Asynchronous coroutine to fetch the UserInstance - :returns: Fetched UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance + + :returns: The fetched UserInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + def update( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: """ - Deletes the UserInstance + Update the UserInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The updated UserInstance """ - return self._version.delete('delete', self._uri) - def update(self, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset): + 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: """ - Update the UserInstance + Asynchronous coroutine to update the UserInstance - :param unicode role_sid: The role_sid - :param unicode attributes: The attributes - :param unicode friendly_name: The friendly_name + :param role_sid: + :param attributes: + :param friendly_name: - :returns: Updated UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance + :returns: The updated UserInstance """ - data = values.of({'RoleSid': role_sid, 'Attributes': attributes, 'FriendlyName': friendly_name, }) - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) @property - def user_channels(self): + def user_channels(self) -> UserChannelList: """ Access the user_channels - - :returns: twilio.rest.chat.v1.service.user.user_channel.UserChannelList - :rtype: twilio.rest.chat.v1.service.user.user_channel.UserChannelList """ if self._user_channels is None: self._user_channels = UserChannelList( self._version, - service_sid=self._solution['service_sid'], - user_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) return self._user_channels - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class UserInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the UserInstance - - :returns: twilio.rest.chat.v1.service.user.UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance - """ - super(UserInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'attributes': payload['attributes'], - 'friendly_name': payload['friendly_name'], - 'role_sid': payload['role_sid'], - 'identity': payload['identity'], - 'is_online': payload['is_online'], - 'is_notifiable': payload['is_notifiable'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'joined_channels_count': deserialize.integer(payload['joined_channels_count']), - 'links': payload['links'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } +class UserPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> UserInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of UserInstance - :returns: UserContext for this UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = UserContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def sid(self): + def __repr__(self) -> str: """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] - @property - def attributes(self): - """ - :returns: The attributes - :rtype: unicode - """ - return self._properties['attributes'] +class UserList(ListResource): - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode + def __init__(self, version: Version, service_sid: str): """ - return self._properties['friendly_name'] + Initialize the UserList - @property - def role_sid(self): - """ - :returns: The role_sid - :rtype: unicode - """ - return self._properties['role_sid'] + :param version: Version that contains the resource + :param service_sid: - @property - def identity(self): """ - :returns: The identity - :rtype: unicode + 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: """ - return self._properties['identity'] + Create the UserInstance - @property - def is_online(self): + :param identity: + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The created UserInstance """ - :returns: The is_online - :rtype: bool + + 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: """ - return self._properties['is_online'] + Asynchronously create the UserInstance - @property - def is_notifiable(self): + :param identity: + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The created UserInstance """ - :returns: The is_notifiable - :rtype: bool + + 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]: """ - return self._properties['is_notifiable'] + 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. - @property - def date_created(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The date_created - :rtype: datetime + 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]: """ - return self._properties['date_created'] + 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. - @property - def date_updated(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The date_updated - :rtype: datetime + 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]: """ - return self._properties['date_updated'] + Lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def joined_channels_count(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The joined_channels_count - :rtype: unicode + 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]: """ - return self._properties['joined_channels_count'] + 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. - @property - def links(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The links - :rtype: unicode + 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: """ - return self._properties['links'] + Retrieve a single page of UserInstance records from the API. + Request is executed immediately - @property - def url(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The url - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of UserInstance """ - Fetch a 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) - :returns: Fetched UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance + def get_page(self, target_url: str) -> UserPage: """ - return self._proxy.fetch() + Retrieve a specific page of UserInstance records from the API. + Request is executed immediately - def delete(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance """ - Deletes the UserInstance + response = self._version.domain.twilio.request("GET", target_url) + return UserPage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def get_page_async(self, target_url: str) -> UserPage: """ - return self._proxy.delete() + 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 - def update(self, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset): + :returns: Page of UserInstance """ - Update the UserInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserPage(self._version, response, self._solution) - :param unicode role_sid: The role_sid - :param unicode attributes: The attributes - :param unicode friendly_name: The friendly_name + def get(self, sid: str) -> UserContext: + """ + Constructs a UserContext - :returns: Updated UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance + :param sid: """ - return self._proxy.update(role_sid=role_sid, attributes=attributes, friendly_name=friendly_name, ) + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - @property - def user_channels(self): + def __call__(self, sid: str) -> UserContext: """ - Access the user_channels + Constructs a UserContext - :returns: twilio.rest.chat.v1.service.user.user_channel.UserChannelList - :rtype: twilio.rest.chat.v1.service.user.user_channel.UserChannelList + :param sid: """ - return self._proxy.user_channels + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/ip_messaging/v1/service/user/user_channel.py b/twilio/rest/ip_messaging/v1/service/user/user_channel.py index 9941c0b627..4245449869 100644 --- a/twilio/rest/ip_messaging/v1/service/user/user_channel.py +++ b/twilio/rest/ip_messaging/v1/service/user/user_channel.py @@ -1,277 +1,322 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 UserChannelList(ListResource): - """ """ - - def __init__(self, version, service_sid, user_sid): - """ - Initialize the UserChannelList +class UserChannelInstance(InstanceResource): - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param user_sid: The sid + class ChannelStatus(object): + JOINED = "joined" + INVITED = "invited" + NOT_PARTICIPATING = "not_participating" - :returns: twilio.rest.chat.v1.service.user.user_channel.UserChannelList - :rtype: twilio.rest.chat.v1.service.user.user_channel.UserChannelList - """ - super(UserChannelList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'service_sid': service_sid, 'user_sid': user_sid, } - self._uri = '/Services/{service_sid}/Users/{user_sid}/Channels'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + } - def stream(self, limit=None, page_size=None): + def __repr__(self) -> str: """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Provide a friendly representation - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.user.user_channel.UserChannelInstance] + :returns: Machine friendly representation """ - limits = self._version.read_limits(limit, page_size) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) +class UserChannelPage(Page): - def list(self, limit=None, page_size=None): + def get_instance(self, payload: Dict[str, Any]) -> 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + Build an instance of UserChannelInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.service.user.user_channel.UserChannelInstance] + :param payload: Payload response from the API """ - return list(self.stream(limit=limit, page_size=page_size, )) + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + ) - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def __repr__(self) -> str: """ - Retrieve a single page of UserChannelInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + Provide a friendly representation - :returns: Page of UserChannelInstance - :rtype: twilio.rest.chat.v1.service.user.user_channel.UserChannelPage + :returns: Machine friendly representation """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return "" - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - return UserChannelPage(self._version, response, self._solution) +class UserChannelList(ListResource): - def get_page(self, target_url): + def __init__(self, version: Version, service_sid: str, user_sid: str): """ - Retrieve a specific page of UserChannelInstance records from the API. - Request is executed immediately + Initialize the UserChannelList - :param str target_url: API-generated URL for the requested results page + :param version: Version that contains the resource + :param service_sid: + :param user_sid: - :returns: Page of UserChannelInstance - :rtype: twilio.rest.chat.v1.service.user.user_channel.UserChannelPage """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + super().__init__(version) - return UserChannelPage(self._version, response, self._solution) + # 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 __repr__(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserChannelInstance]: """ - Provide a friendly representation + 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. - :returns: Machine friendly representation - :rtype: str - """ - return '' + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.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"]) -class UserChannelPage(Page): - """ """ + return self._version.stream(page, limits["limit"]) - def __init__(self, version, response, solution): + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserChannelInstance]: """ - Initialize the UserChannelPage + 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 Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :param user_sid: The 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: twilio.rest.chat.v1.service.user.user_channel.UserChannelPage - :rtype: twilio.rest.chat.v1.service.user.user_channel.UserChannelPage + :returns: Generator that will yield up to limit results """ - super(UserChannelPage, self).__init__(version, response) + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - # Path Solution - self._solution = solution + return self._version.stream_async(page, limits["limit"]) - def get_instance(self, payload): + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: """ - Build an instance of 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 dict payload: Payload response from the API + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - :returns: twilio.rest.chat.v1.service.user.user_channel.UserChannelInstance - :rtype: twilio.rest.chat.v1.service.user.user_channel.UserChannelInstance + :returns: list that will contain up to limit results """ - return UserChannelInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], + return list( + self.stream( + limit=limit, + page_size=page_size, + ) ) - def __repr__(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: """ - Provide a friendly representation + 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. - :returns: Machine friendly representation - :rtype: str + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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: """ - return '' + 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 -class UserChannelInstance(InstanceResource): - """ """ + :returns: Page of UserChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - class ChannelStatus(object): - JOINED = "joined" - INVITED = "invited" - NOT_PARTICIPATING = "not_participating" + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def __init__(self, version, payload, service_sid, user_sid): - """ - Initialize the UserChannelInstance + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserChannelPage(self._version, response, self._solution) - :returns: twilio.rest.chat.v1.service.user.user_channel.UserChannelInstance - :rtype: twilio.rest.chat.v1.service.user.user_channel.UserChannelInstance + 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: """ - super(UserChannelInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'channel_sid': payload['channel_sid'], - 'member_sid': payload['member_sid'], - 'status': payload['status'], - 'last_consumed_message_index': deserialize.integer(payload['last_consumed_message_index']), - 'unread_messages_count': deserialize.integer(payload['unread_messages_count']), - 'links': payload['links'], - } + Asynchronously retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'user_sid': user_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 - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + :returns: Page of UserChannelInstance """ - return self._properties['account_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def channel_sid(self): - """ - :returns: The channel_sid - :rtype: unicode - """ - return self._properties['channel_sid'] + headers["Accept"] = "application/json" - @property - def member_sid(self): - """ - :returns: The member_sid - :rtype: unicode - """ - return self._properties['member_sid'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserChannelPage(self._version, response, self._solution) - @property - def status(self): + def get_page(self, target_url: str) -> UserChannelPage: """ - :returns: The status - :rtype: UserChannelInstance.ChannelStatus - """ - return self._properties['status'] + Retrieve a specific page of UserChannelInstance records from the API. + Request is executed immediately - @property - def last_consumed_message_index(self): - """ - :returns: The last_consumed_message_index - :rtype: unicode - """ - return self._properties['last_consumed_message_index'] + :param target_url: API-generated URL for the requested results page - @property - def unread_messages_count(self): - """ - :returns: The unread_messages_count - :rtype: unicode + :returns: Page of UserChannelInstance """ - return self._properties['unread_messages_count'] + response = self._version.domain.twilio.request("GET", target_url) + return UserChannelPage(self._version, response, self._solution) - @property - def links(self): + async def get_page_async(self, target_url: str) -> UserChannelPage: """ - :returns: The links - :rtype: unicode + 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 """ - return self._properties['links'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserChannelPage(self._version, response, self._solution) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/ip_messaging/v2/__init__.py b/twilio/rest/ip_messaging/v2/__init__.py index 7a7a4384f9..6003c86b12 100644 --- a/twilio/rest/ip_messaging/v2/__init__.py +++ b/twilio/rest/ip_messaging/v2/__init__.py @@ -1,53 +1,51 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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): + def __init__(self, domain: Domain): """ Initialize the V2 version of IpMessaging - :returns: V2 version of IpMessaging - :rtype: twilio.rest.ip_messaging.v2.V2.V2 + :param domain: The Twilio.ip_messaging domain """ - super(V2, self).__init__(domain) - self.version = 'v2' - self._credentials = None - self._services = None + super().__init__(domain, "v2") + self._credentials: Optional[CredentialList] = None + self._services: Optional[ServiceList] = None @property - def credentials(self): - """ - :rtype: twilio.rest.chat.v2.credential.CredentialList - """ + def credentials(self) -> CredentialList: if self._credentials is None: self._credentials = CredentialList(self) return self._credentials @property - def services(self): - """ - :rtype: twilio.rest.chat.v2.service.ServiceList - """ + def services(self) -> ServiceList: if self._services is None: self._services = ServiceList(self) return self._services - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/ip_messaging/v2/credential.py b/twilio/rest/ip_messaging/v2/credential.py index fe38d5e2c5..065c5048e9 100644 --- a/twilio/rest/ip_messaging/v2/credential.py +++ b/twilio/rest/ip_messaging/v2/credential.py @@ -1,472 +1,711 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 CredentialList(ListResource): - """ """ - - def __init__(self, version): - """ - Initialize the CredentialList +class CredentialInstance(InstanceResource): - :param Version version: Version that contains the resource + class PushService(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" - :returns: twilio.rest.chat.v2.credential.CredentialList - :rtype: twilio.rest.chat.v2.credential.CredentialList - """ - super(CredentialList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {} - self._uri = '/Credentials'.format(**self._solution) + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CredentialContext] = None - def stream(self, limit=None, page_size=None): + @property + def _proxy(self) -> "CredentialContext": """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.credential.CredentialInstance] + :returns: CredentialContext for this CredentialInstance """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def list(self, limit=None, page_size=None): + def delete(self) -> bool: """ - Lists CredentialInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the CredentialInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.credential.CredentialInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.delete() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def delete_async(self) -> bool: """ - Retrieve a single page of CredentialInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the CredentialInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialPage + :returns: True if delete succeeds, False otherwise """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + return await self._proxy.delete_async() - return CredentialPage(self._version, response, self._solution) - - def get_page(self, target_url): + def fetch(self) -> "CredentialInstance": """ - Retrieve a specific page of CredentialInstance records from the API. - Request is executed immediately + Fetch the CredentialInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialPage + :returns: The fetched CredentialInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return CredentialPage(self._version, response, self._solution) + return self._proxy.fetch() - def create(self, type, friendly_name=values.unset, certificate=values.unset, - private_key=values.unset, sandbox=values.unset, api_key=values.unset, - secret=values.unset): + async def fetch_async(self) -> "CredentialInstance": """ - Create a new CredentialInstance + Asynchronous coroutine to fetch the CredentialInstance - :param CredentialInstance.PushService type: The type - :param unicode friendly_name: The friendly_name - :param unicode certificate: The certificate - :param unicode private_key: The private_key - :param bool sandbox: The sandbox - :param unicode api_key: The api_key - :param unicode secret: The secret - :returns: Newly created CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance + :returns: The fetched CredentialInstance """ - data = values.of({ - 'Type': type, - 'FriendlyName': friendly_name, - 'Certificate': certificate, - 'PrivateKey': private_key, - 'Sandbox': sandbox, - 'ApiKey': api_key, - 'Secret': secret, - }) + return await self._proxy.fetch_async() - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return CredentialInstance(self._version, payload, ) - - def get(self, 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": """ - Constructs a CredentialContext + Update the CredentialInstance - :param sid: The sid + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: - :returns: twilio.rest.chat.v2.credential.CredentialContext - :rtype: twilio.rest.chat.v2.credential.CredentialContext + :returns: The updated CredentialInstance """ - return CredentialContext(self._version, sid=sid, ) + return self._proxy.update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - def __call__(self, 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": """ - Constructs a CredentialContext + Asynchronous coroutine to update the CredentialInstance - :param sid: The sid + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: - :returns: twilio.rest.chat.v2.credential.CredentialContext - :rtype: twilio.rest.chat.v2.credential.CredentialContext + :returns: The updated CredentialInstance """ - return CredentialContext(self._version, sid=sid, ) + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class CredentialPage(Page): - """ """ +class CredentialContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the CredentialPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the CredentialContext - :returns: twilio.rest.chat.v2.credential.CredentialPage - :rtype: twilio.rest.chat.v2.credential.CredentialPage + :param version: Version that contains the resource + :param sid: """ - super(CredentialPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) - def get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of CredentialInstance + Deletes the CredentialInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v2.credential.CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance + :returns: True if delete succeeds, False otherwise """ - return CredentialInstance(self._version, payload, ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the CredentialInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class CredentialContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, sid): + def fetch(self) -> CredentialInstance: """ - Initialize the CredentialContext + Fetch the CredentialInstance - :param Version version: Version that contains the resource - :param sid: The sid - :returns: twilio.rest.chat.v2.credential.CredentialContext - :rtype: twilio.rest.chat.v2.credential.CredentialContext + :returns: The fetched CredentialInstance """ - super(CredentialContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Credentials/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialInstance: """ - Fetch a CredentialInstance + Asynchronous coroutine to fetch the CredentialInstance - :returns: Fetched CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance + + :returns: The fetched CredentialInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], ) + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def update(self, friendly_name=values.unset, certificate=values.unset, - private_key=values.unset, sandbox=values.unset, api_key=values.unset, - secret=values.unset): + 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 unicode friendly_name: The friendly_name - :param unicode certificate: The certificate - :param unicode private_key: The private_key - :param bool sandbox: The sandbox - :param unicode api_key: The api_key - :param unicode secret: The secret - - :returns: Updated CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Certificate': certificate, - 'PrivateKey': private_key, - 'Sandbox': sandbox, - 'ApiKey': api_key, - 'Secret': secret, - }) + :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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) - return CredentialInstance(self._version, payload, sid=self._solution['sid'], ) + 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({}) - def delete(self): - """ - Deletes the CredentialInstance + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + headers["Accept"] = "application/json" - def __repr__(self): + 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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class CredentialInstance(InstanceResource): - """ """ +class CredentialPage(Page): - class PushService(object): - GCM = "gcm" - APN = "apn" - FCM = "fcm" + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: + """ + Build an instance of CredentialInstance - def __init__(self, version, payload, sid=None): + :param payload: Payload response from the API """ - Initialize the CredentialInstance + return CredentialInstance(self._version, payload) - :returns: twilio.rest.chat.v2.credential.CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance + def __repr__(self) -> str: """ - super(CredentialInstance, self).__init__(version) + Provide a friendly representation - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'friendly_name': payload['friendly_name'], - 'type': payload['type'], - 'sandbox': payload['sandbox'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - } + :returns: Machine friendly representation + """ + return "" - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context +class CredentialList(ListResource): - :returns: CredentialContext for this CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialContext + def __init__(self, version: Version): """ - if self._context is None: - self._context = CredentialContext(self._version, sid=self._solution['sid'], ) - return self._context + Initialize the CredentialList + + :param version: Version that contains the resource - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode """ - return self._properties['sid'] + super().__init__(version) - @property - def account_sid(self): + 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: """ - :returns: The account_sid - :rtype: unicode + Create the CredentialInstance + + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The created CredentialInstance """ - return self._properties['account_sid'] - @property - def friendly_name(self): + 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]: """ - :returns: The friendly_name - :rtype: unicode + 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 """ - return self._properties['friendly_name'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def type(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialInstance]: """ - :returns: The type - :rtype: CredentialInstance.PushService + 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 """ - return self._properties['type'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def sandbox(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: """ - :returns: The sandbox - :rtype: unicode + 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 self._properties['sandbox'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def date_created(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: """ - :returns: The date_created - :rtype: datetime + 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: """ - return self._properties['date_created'] + Retrieve a single page of CredentialInstance records from the API. + Request is executed immediately - @property - def date_updated(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The date_updated - :rtype: datetime + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page of CredentialInstance records from the API. + Request is executed immediately - @property - def url(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The url - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['url'] + Retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance """ - Fetch a CredentialInstance + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) - :returns: Fetched CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance + async def get_page_async(self, target_url: str) -> CredentialPage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately - def update(self, friendly_name=values.unset, certificate=values.unset, - private_key=values.unset, sandbox=values.unset, api_key=values.unset, - secret=values.unset): + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance """ - Update the CredentialInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response) - :param unicode friendly_name: The friendly_name - :param unicode certificate: The certificate - :param unicode private_key: The private_key - :param bool sandbox: The sandbox - :param unicode api_key: The api_key - :param unicode secret: The secret + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext - :returns: Updated CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance + :param sid: """ - return self._proxy.update( - friendly_name=friendly_name, - certificate=certificate, - private_key=private_key, - sandbox=sandbox, - api_key=api_key, - secret=secret, - ) + return CredentialContext(self._version, sid=sid) - def delete(self): + def __call__(self, sid: str) -> CredentialContext: """ - Deletes the CredentialInstance + Constructs a CredentialContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: """ - return self._proxy.delete() + return CredentialContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/ip_messaging/v2/service/__init__.py b/twilio/rest/ip_messaging/v2/service/__init__.py index 8c305bc451..a303f10f33 100644 --- a/twilio/rest/ip_messaging/v2/service/__init__.py +++ b/twilio/rest/ip_messaging/v2/service/__init__.py @@ -1,17 +1,24 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 @@ -19,817 +26,1103 @@ from twilio.rest.ip_messaging.v2.service.user import UserList -class ServiceList(ListResource): - """ """ - - def __init__(self, version): - """ - Initialize the ServiceList +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") - :param Version version: Version that contains the resource + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None - :returns: twilio.rest.chat.v2.service.ServiceList - :rtype: twilio.rest.chat.v2.service.ServiceList + @property + def _proxy(self) -> "ServiceContext": """ - super(ServiceList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Services'.format(**self._solution) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def create(self, friendly_name): + :returns: ServiceContext for this ServiceInstance """ - Create a new ServiceInstance - - :param unicode friendly_name: The friendly_name + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: Newly created ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance + def delete(self) -> bool: """ - data = values.of({'FriendlyName': friendly_name, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + Deletes the ServiceInstance - return ServiceInstance(self._version, payload, ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.ServiceInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the ServiceInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the ServiceInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.ServiceInstance] + :returns: The fetched ServiceInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + 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": """ - Retrieve a single page of ServiceInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + Update the ServiceInstance - :returns: Page of ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServicePage + :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 """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + 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, ) - return ServicePage(self._version, response, self._solution) + 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, + ) - def get_page(self, target_url): + @property + def bindings(self) -> BindingList: """ - Retrieve a specific page of ServiceInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServicePage + Access the bindings """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ServicePage(self._version, response, self._solution) + return self._proxy.bindings - def get(self, sid): + @property + def channels(self) -> ChannelList: """ - Constructs a ServiceContext - - :param sid: The sid - - :returns: twilio.rest.chat.v2.service.ServiceContext - :rtype: twilio.rest.chat.v2.service.ServiceContext + Access the channels """ - return ServiceContext(self._version, sid=sid, ) + return self._proxy.channels - def __call__(self, sid): + @property + def roles(self) -> RoleList: """ - Constructs a ServiceContext - - :param sid: The sid + Access the roles + """ + return self._proxy.roles - :returns: twilio.rest.chat.v2.service.ServiceContext - :rtype: twilio.rest.chat.v2.service.ServiceContext + @property + def users(self) -> UserList: """ - return ServiceContext(self._version, sid=sid, ) + Access the users + """ + return self._proxy.users - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ServicePage(Page): - """ """ +class ServiceContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the ServicePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the ServiceContext - :returns: twilio.rest.chat.v2.service.ServicePage - :rtype: twilio.rest.chat.v2.service.ServicePage + :param version: Version that contains the resource + :param sid: """ - super(ServicePage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of ServiceInstance + Deletes the ServiceInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v2.service.ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance + :returns: True if delete succeeds, False otherwise """ - return ServiceInstance(self._version, payload, ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the ServiceInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class ServiceContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, sid): + def fetch(self) -> ServiceInstance: """ - Initialize the ServiceContext + Fetch the ServiceInstance - :param Version version: Version that contains the resource - :param sid: The sid - :returns: twilio.rest.chat.v2.service.ServiceContext - :rtype: twilio.rest.chat.v2.service.ServiceContext + :returns: The fetched ServiceInstance """ - super(ServiceContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Services/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - # Dependents - self._channels = None - self._roles = None - self._users = None - self._bindings = None + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def fetch(self): + async def fetch_async(self) -> ServiceInstance: """ - Fetch a ServiceInstance + Asynchronous coroutine to fetch the ServiceInstance + - :returns: Fetched ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance + :returns: The fetched ServiceInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) + headers = values.of({}) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" - def delete(self): - """ - Deletes the ServiceInstance + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def update(self, friendly_name=values.unset, - default_service_role_sid=values.unset, - default_channel_role_sid=values.unset, - default_channel_creator_role_sid=values.unset, - read_status_enabled=values.unset, reachability_enabled=values.unset, - typing_indicator_timeout=values.unset, - consumption_report_interval=values.unset, - notifications_new_message_enabled=values.unset, - notifications_new_message_template=values.unset, - notifications_new_message_sound=values.unset, - notifications_new_message_badge_count_enabled=values.unset, - notifications_added_to_channel_enabled=values.unset, - notifications_added_to_channel_template=values.unset, - notifications_added_to_channel_sound=values.unset, - notifications_removed_from_channel_enabled=values.unset, - notifications_removed_from_channel_template=values.unset, - notifications_removed_from_channel_sound=values.unset, - notifications_invited_to_channel_enabled=values.unset, - notifications_invited_to_channel_template=values.unset, - notifications_invited_to_channel_sound=values.unset, - pre_webhook_url=values.unset, post_webhook_url=values.unset, - webhook_method=values.unset, webhook_filters=values.unset, - limits_channel_members=values.unset, - limits_user_channels=values.unset, - media_compatibility_message=values.unset, - pre_webhook_retry_count=values.unset, - post_webhook_retry_count=values.unset, - notifications_log_enabled=values.unset): + 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 unicode friendly_name: The friendly_name - :param unicode default_service_role_sid: The default_service_role_sid - :param unicode default_channel_role_sid: The default_channel_role_sid - :param unicode default_channel_creator_role_sid: The default_channel_creator_role_sid - :param bool read_status_enabled: The read_status_enabled - :param bool reachability_enabled: The reachability_enabled - :param unicode typing_indicator_timeout: The typing_indicator_timeout - :param unicode consumption_report_interval: The consumption_report_interval - :param bool notifications_new_message_enabled: The notifications.new_message.enabled - :param unicode notifications_new_message_template: The notifications.new_message.template - :param unicode notifications_new_message_sound: The notifications.new_message.sound - :param bool notifications_new_message_badge_count_enabled: The notifications.new_message.badge_count_enabled - :param bool notifications_added_to_channel_enabled: The notifications.added_to_channel.enabled - :param unicode notifications_added_to_channel_template: The notifications.added_to_channel.template - :param unicode notifications_added_to_channel_sound: The notifications.added_to_channel.sound - :param bool notifications_removed_from_channel_enabled: The notifications.removed_from_channel.enabled - :param unicode notifications_removed_from_channel_template: The notifications.removed_from_channel.template - :param unicode notifications_removed_from_channel_sound: The notifications.removed_from_channel.sound - :param bool notifications_invited_to_channel_enabled: The notifications.invited_to_channel.enabled - :param unicode notifications_invited_to_channel_template: The notifications.invited_to_channel.template - :param unicode notifications_invited_to_channel_sound: The notifications.invited_to_channel.sound - :param unicode pre_webhook_url: The pre_webhook_url - :param unicode post_webhook_url: The post_webhook_url - :param unicode webhook_method: The webhook_method - :param unicode webhook_filters: The webhook_filters - :param unicode limits_channel_members: The limits.channel_members - :param unicode limits_user_channels: The limits.user_channels - :param unicode media_compatibility_message: The media.compatibility_message - :param unicode pre_webhook_retry_count: The pre_webhook_retry_count - :param unicode post_webhook_retry_count: The post_webhook_retry_count - :param bool notifications_log_enabled: The notifications.log_enabled - - :returns: Updated ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'DefaultServiceRoleSid': default_service_role_sid, - 'DefaultChannelRoleSid': default_channel_role_sid, - 'DefaultChannelCreatorRoleSid': default_channel_creator_role_sid, - 'ReadStatusEnabled': read_status_enabled, - 'ReachabilityEnabled': reachability_enabled, - 'TypingIndicatorTimeout': typing_indicator_timeout, - 'ConsumptionReportInterval': consumption_report_interval, - 'Notifications.NewMessage.Enabled': notifications_new_message_enabled, - 'Notifications.NewMessage.Template': notifications_new_message_template, - 'Notifications.NewMessage.Sound': notifications_new_message_sound, - 'Notifications.NewMessage.BadgeCountEnabled': notifications_new_message_badge_count_enabled, - 'Notifications.AddedToChannel.Enabled': notifications_added_to_channel_enabled, - 'Notifications.AddedToChannel.Template': notifications_added_to_channel_template, - 'Notifications.AddedToChannel.Sound': notifications_added_to_channel_sound, - 'Notifications.RemovedFromChannel.Enabled': notifications_removed_from_channel_enabled, - 'Notifications.RemovedFromChannel.Template': notifications_removed_from_channel_template, - 'Notifications.RemovedFromChannel.Sound': notifications_removed_from_channel_sound, - 'Notifications.InvitedToChannel.Enabled': 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': notifications_log_enabled, - }) + :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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + 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 channels(self): + def bindings(self) -> BindingList: """ - Access the channels + Access the bindings + """ + if self._bindings is None: + self._bindings = BindingList( + self._version, + self._solution["sid"], + ) + return self._bindings - :returns: twilio.rest.chat.v2.service.channel.ChannelList - :rtype: twilio.rest.chat.v2.service.channel.ChannelList + @property + def channels(self) -> ChannelList: + """ + Access the channels """ if self._channels is None: - self._channels = ChannelList(self._version, service_sid=self._solution['sid'], ) + self._channels = ChannelList( + self._version, + self._solution["sid"], + ) return self._channels @property - def roles(self): + def roles(self) -> RoleList: """ Access the roles - - :returns: twilio.rest.chat.v2.service.role.RoleList - :rtype: twilio.rest.chat.v2.service.role.RoleList """ if self._roles is None: - self._roles = RoleList(self._version, service_sid=self._solution['sid'], ) + self._roles = RoleList( + self._version, + self._solution["sid"], + ) return self._roles @property - def users(self): + def users(self) -> UserList: """ Access the users - - :returns: twilio.rest.chat.v2.service.user.UserList - :rtype: twilio.rest.chat.v2.service.user.UserList """ if self._users is None: - self._users = UserList(self._version, service_sid=self._solution['sid'], ) + self._users = UserList( + self._version, + self._solution["sid"], + ) return self._users - @property - def bindings(self): - """ - Access the bindings - - :returns: twilio.rest.chat.v2.service.binding.BindingList - :rtype: twilio.rest.chat.v2.service.binding.BindingList - """ - if self._bindings is None: - self._bindings = BindingList(self._version, service_sid=self._solution['sid'], ) - return self._bindings - - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ServiceInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, sid=None): - """ - Initialize the ServiceInstance - - :returns: twilio.rest.chat.v2.service.ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance - """ - super(ServiceInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'friendly_name': payload['friendly_name'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'default_service_role_sid': payload['default_service_role_sid'], - 'default_channel_role_sid': payload['default_channel_role_sid'], - 'default_channel_creator_role_sid': payload['default_channel_creator_role_sid'], - 'read_status_enabled': payload['read_status_enabled'], - 'reachability_enabled': payload['reachability_enabled'], - 'typing_indicator_timeout': deserialize.integer(payload['typing_indicator_timeout']), - 'consumption_report_interval': deserialize.integer(payload['consumption_report_interval']), - 'limits': payload['limits'], - 'pre_webhook_url': payload['pre_webhook_url'], - 'post_webhook_url': payload['post_webhook_url'], - 'webhook_method': payload['webhook_method'], - 'webhook_filters': payload['webhook_filters'], - 'pre_webhook_retry_count': deserialize.integer(payload['pre_webhook_retry_count']), - 'post_webhook_retry_count': deserialize.integer(payload['post_webhook_retry_count']), - 'notifications': payload['notifications'], - 'media': payload['media'], - 'url': payload['url'], - 'links': payload['links'], - } - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } +class ServicePage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of ServiceInstance - :returns: ServiceContext for this ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = ServiceContext(self._version, sid=self._solution['sid'], ) - return self._context + return ServiceInstance(self._version, payload) - @property - def sid(self): + def __repr__(self) -> str: """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] +class ServiceList(ListResource): - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime + def __init__(self, version: Version): """ - return self._properties['date_updated'] + Initialize the ServiceList - @property - def default_service_role_sid(self): - """ - :returns: The default_service_role_sid - :rtype: unicode - """ - return self._properties['default_service_role_sid'] + :param version: Version that contains the resource - @property - def default_channel_role_sid(self): - """ - :returns: The default_channel_role_sid - :rtype: unicode """ - return self._properties['default_channel_role_sid'] + super().__init__(version) - @property - def default_channel_creator_role_sid(self): - """ - :returns: The default_channel_creator_role_sid - :rtype: unicode - """ - return self._properties['default_channel_creator_role_sid'] + self._uri = "/Services" - @property - def read_status_enabled(self): + def create(self, friendly_name: str) -> ServiceInstance: """ - :returns: The read_status_enabled - :rtype: bool - """ - return self._properties['read_status_enabled'] + Create the ServiceInstance - @property - def reachability_enabled(self): - """ - :returns: The reachability_enabled - :rtype: bool - """ - return self._properties['reachability_enabled'] + :param friendly_name: - @property - def typing_indicator_timeout(self): + :returns: The created ServiceInstance """ - :returns: The typing_indicator_timeout - :rtype: unicode - """ - return self._properties['typing_indicator_timeout'] - @property - def consumption_report_interval(self): - """ - :returns: The consumption_report_interval - :rtype: unicode - """ - return self._properties['consumption_report_interval'] + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def limits(self): - """ - :returns: The limits - :rtype: dict - """ - return self._properties['limits'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def pre_webhook_url(self): - """ - :returns: The pre_webhook_url - :rtype: unicode - """ - return self._properties['pre_webhook_url'] + headers["Accept"] = "application/json" - @property - def post_webhook_url(self): - """ - :returns: The post_webhook_url - :rtype: unicode - """ - return self._properties['post_webhook_url'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def webhook_method(self): - """ - :returns: The webhook_method - :rtype: unicode - """ - return self._properties['webhook_method'] + return ServiceInstance(self._version, payload) - @property - def webhook_filters(self): - """ - :returns: The webhook_filters - :rtype: unicode + async def create_async(self, friendly_name: str) -> ServiceInstance: """ - return self._properties['webhook_filters'] + Asynchronously create the ServiceInstance - @property - def pre_webhook_retry_count(self): - """ - :returns: The pre_webhook_retry_count - :rtype: unicode - """ - return self._properties['pre_webhook_retry_count'] + :param friendly_name: - @property - def post_webhook_retry_count(self): - """ - :returns: The post_webhook_retry_count - :rtype: unicode + :returns: The created ServiceInstance """ - return self._properties['post_webhook_retry_count'] - @property - def notifications(self): - """ - :returns: The notifications - :rtype: dict - """ - return self._properties['notifications'] + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def media(self): - """ - :returns: The media - :rtype: dict + 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]: """ - return self._properties['media'] + 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. - @property - def url(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The url - :rtype: unicode + 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]: """ - return self._properties['url'] + 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. - @property - def links(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The links - :rtype: unicode + 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]: """ - return self._properties['links'] + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - def fetch(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - Fetch a ServiceInstance + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - :returns: Fetched ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: """ - return self._proxy.fetch() + 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. - def delete(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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: """ - Deletes the ServiceInstance + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param page_token: PageToken provided by the API + :param page_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 """ - return self._proxy.delete() + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" - def update(self, friendly_name=values.unset, - default_service_role_sid=values.unset, - default_channel_role_sid=values.unset, - default_channel_creator_role_sid=values.unset, - read_status_enabled=values.unset, reachability_enabled=values.unset, - typing_indicator_timeout=values.unset, - consumption_report_interval=values.unset, - notifications_new_message_enabled=values.unset, - notifications_new_message_template=values.unset, - notifications_new_message_sound=values.unset, - notifications_new_message_badge_count_enabled=values.unset, - notifications_added_to_channel_enabled=values.unset, - notifications_added_to_channel_template=values.unset, - notifications_added_to_channel_sound=values.unset, - notifications_removed_from_channel_enabled=values.unset, - notifications_removed_from_channel_template=values.unset, - notifications_removed_from_channel_sound=values.unset, - notifications_invited_to_channel_enabled=values.unset, - notifications_invited_to_channel_template=values.unset, - notifications_invited_to_channel_sound=values.unset, - pre_webhook_url=values.unset, post_webhook_url=values.unset, - webhook_method=values.unset, webhook_filters=values.unset, - limits_channel_members=values.unset, - limits_user_channels=values.unset, - media_compatibility_message=values.unset, - pre_webhook_retry_count=values.unset, - post_webhook_retry_count=values.unset, - notifications_log_enabled=values.unset): + 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: """ - Update the ServiceInstance + 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 - :param unicode friendly_name: The friendly_name - :param unicode default_service_role_sid: The default_service_role_sid - :param unicode default_channel_role_sid: The default_channel_role_sid - :param unicode default_channel_creator_role_sid: The default_channel_creator_role_sid - :param bool read_status_enabled: The read_status_enabled - :param bool reachability_enabled: The reachability_enabled - :param unicode typing_indicator_timeout: The typing_indicator_timeout - :param unicode consumption_report_interval: The consumption_report_interval - :param bool notifications_new_message_enabled: The notifications.new_message.enabled - :param unicode notifications_new_message_template: The notifications.new_message.template - :param unicode notifications_new_message_sound: The notifications.new_message.sound - :param bool notifications_new_message_badge_count_enabled: The notifications.new_message.badge_count_enabled - :param bool notifications_added_to_channel_enabled: The notifications.added_to_channel.enabled - :param unicode notifications_added_to_channel_template: The notifications.added_to_channel.template - :param unicode notifications_added_to_channel_sound: The notifications.added_to_channel.sound - :param bool notifications_removed_from_channel_enabled: The notifications.removed_from_channel.enabled - :param unicode notifications_removed_from_channel_template: The notifications.removed_from_channel.template - :param unicode notifications_removed_from_channel_sound: The notifications.removed_from_channel.sound - :param bool notifications_invited_to_channel_enabled: The notifications.invited_to_channel.enabled - :param unicode notifications_invited_to_channel_template: The notifications.invited_to_channel.template - :param unicode notifications_invited_to_channel_sound: The notifications.invited_to_channel.sound - :param unicode pre_webhook_url: The pre_webhook_url - :param unicode post_webhook_url: The post_webhook_url - :param unicode webhook_method: The webhook_method - :param unicode webhook_filters: The webhook_filters - :param unicode limits_channel_members: The limits.channel_members - :param unicode limits_user_channels: The limits.user_channels - :param unicode media_compatibility_message: The media.compatibility_message - :param unicode pre_webhook_retry_count: The pre_webhook_retry_count - :param unicode post_webhook_retry_count: The post_webhook_retry_count - :param bool notifications_log_enabled: The notifications.log_enabled - - :returns: Updated ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance + :returns: Page of 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, + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } ) - @property - def channels(self): + headers = values.of({"Content-Type": "application/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: """ - Access the channels + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately - :returns: twilio.rest.chat.v2.service.channel.ChannelList - :rtype: twilio.rest.chat.v2.service.channel.ChannelList + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance """ - return self._proxy.channels + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) - @property - def roles(self): + async def get_page_async(self, target_url: str) -> ServicePage: """ - Access the roles + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately - :returns: twilio.rest.chat.v2.service.role.RoleList - :rtype: twilio.rest.chat.v2.service.role.RoleList + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance """ - return self._proxy.roles + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) - @property - def users(self): + def get(self, sid: str) -> ServiceContext: """ - Access the users + Constructs a ServiceContext - :returns: twilio.rest.chat.v2.service.user.UserList - :rtype: twilio.rest.chat.v2.service.user.UserList + :param sid: """ - return self._proxy.users + return ServiceContext(self._version, sid=sid) - @property - def bindings(self): + def __call__(self, sid: str) -> ServiceContext: """ - Access the bindings + Constructs a ServiceContext - :returns: twilio.rest.chat.v2.service.binding.BindingList - :rtype: twilio.rest.chat.v2.service.binding.BindingList + :param sid: """ - return self._proxy.bindings + return ServiceContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/ip_messaging/v2/service/binding.py b/twilio/rest/ip_messaging/v2/service/binding.py index b0c9b8ff82..af9018af9f 100644 --- a/twilio/rest/ip_messaging/v2/service/binding.py +++ b/twilio/rest/ip_messaging/v2/service/binding.py @@ -1,448 +1,536 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 BindingList(ListResource): - """ """ - - def __init__(self, version, service_sid): - """ - Initialize the BindingList +class BindingInstance(InstanceResource): - :param Version version: Version that contains the resource - :param service_sid: The service_sid + class BindingType(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" - :returns: twilio.rest.chat.v2.service.binding.BindingList - :rtype: twilio.rest.chat.v2.service.binding.BindingList - """ - super(BindingList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Bindings'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[BindingContext] = None - def stream(self, binding_type=values.unset, identity=values.unset, limit=None, - page_size=None): + @property + def _proxy(self) -> "BindingContext": """ - 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. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param BindingInstance.BindingType binding_type: The binding_type - :param unicode identity: The identity - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.binding.BindingInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the BindingInstance - page = self.page(binding_type=binding_type, identity=identity, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, binding_type=values.unset, identity=values.unset, limit=None, - page_size=None): + async def delete_async(self) -> bool: """ - Lists BindingInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the BindingInstance - :param BindingInstance.BindingType binding_type: The binding_type - :param unicode identity: The identity - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.binding.BindingInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream( - binding_type=binding_type, - identity=identity, - limit=limit, - page_size=page_size, - )) + return await self._proxy.delete_async() - def page(self, binding_type=values.unset, identity=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "BindingInstance": """ - Retrieve a single page of BindingInstance records from the API. - Request is executed immediately + Fetch the BindingInstance - :param BindingInstance.BindingType binding_type: The binding_type - :param unicode identity: The identity - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of BindingInstance - :rtype: twilio.rest.chat.v2.service.binding.BindingPage + :returns: The fetched BindingInstance """ - params = 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, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return BindingPage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "BindingInstance": """ - Retrieve a specific page of BindingInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the BindingInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of BindingInstance - :rtype: twilio.rest.chat.v2.service.binding.BindingPage + :returns: The fetched BindingInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return await self._proxy.fetch_async() - return BindingPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a BindingContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - :param sid: The sid +class BindingContext(InstanceContext): - :returns: twilio.rest.chat.v2.service.binding.BindingContext - :rtype: twilio.rest.chat.v2.service.binding.BindingContext + def __init__(self, version: Version, service_sid: str, sid: str): """ - return BindingContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Initialize the BindingContext - def __call__(self, sid): + :param version: Version that contains the resource + :param service_sid: + :param sid: """ - Constructs a BindingContext + super().__init__(version) - :param sid: The sid + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Bindings/{sid}".format(**self._solution) - :returns: twilio.rest.chat.v2.service.binding.BindingContext - :rtype: twilio.rest.chat.v2.service.binding.BindingContext + def delete(self) -> bool: """ - return BindingContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Deletes the BindingInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class BindingPage(Page): - """ """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, response, solution): + async def delete_async(self) -> bool: """ - Initialize the BindingPage + Asynchronous coroutine that deletes the BindingInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :returns: twilio.rest.chat.v2.service.binding.BindingPage - :rtype: twilio.rest.chat.v2.service.binding.BindingPage + :returns: True if delete succeeds, False otherwise """ - super(BindingPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): - """ - Build an instance of BindingInstance - - :param dict payload: Payload response from the API + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.chat.v2.service.binding.BindingInstance - :rtype: twilio.rest.chat.v2.service.binding.BindingInstance + def fetch(self) -> BindingInstance: """ - return BindingInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Fetch the BindingInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: The fetched BindingInstance """ - return '' + headers = values.of({}) -class BindingContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, service_sid, sid): - """ - Initialize the BindingContext + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: The sid + return BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.chat.v2.service.binding.BindingContext - :rtype: twilio.rest.chat.v2.service.binding.BindingContext + async def fetch_async(self) -> BindingInstance: """ - super(BindingContext, self).__init__(version) + Asynchronous coroutine to fetch the BindingInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Bindings/{sid}'.format(**self._solution) - def fetch(self): + :returns: The fetched BindingInstance """ - Fetch a BindingInstance - :returns: Fetched BindingInstance - :rtype: twilio.rest.chat.v2.service.binding.BindingInstance - """ - params = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + def __repr__(self) -> str: """ - Deletes the BindingInstance + Provide a friendly representation - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: Machine friendly representation """ - return self._version.delete('delete', self._uri) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - def __repr__(self): + +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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" -class BindingInstance(InstanceResource): - """ """ - - class BindingType(object): - GCM = "gcm" - APN = "apn" - FCM = "fcm" +class BindingList(ListResource): - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the BindingInstance - - :returns: twilio.rest.chat.v2.service.binding.BindingInstance - :rtype: twilio.rest.chat.v2.service.binding.BindingInstance - """ - super(BindingInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'endpoint': payload['endpoint'], - 'identity': payload['identity'], - 'credential_sid': payload['credential_sid'], - 'binding_type': payload['binding_type'], - 'message_types': payload['message_types'], - 'url': payload['url'], - 'links': payload['links'], - } + def __init__(self, version: Version, service_sid: str): + """ + Initialize the BindingList - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + :param version: Version that contains the resource + :param service_sid: - @property - def _proxy(self): """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + super().__init__(version) - :returns: BindingContext for this BindingInstance - :rtype: twilio.rest.chat.v2.service.binding.BindingContext - """ - if self._context is None: - self._context = BindingContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Bindings".format(**self._solution) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + 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]: """ - return self._properties['sid'] + 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. - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + :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) - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['service_sid'] + limits = self._version.read_limits(limit, page_size) + page = self.page( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + return self._version.stream(page, limits["limit"]) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime + 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]: """ - return self._properties['date_updated'] + 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. - @property - def endpoint(self): - """ - :returns: The endpoint - :rtype: unicode - """ - return self._properties['endpoint'] + :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) - @property - def identity(self): - """ - :returns: The identity - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['identity'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) - @property - def credential_sid(self): + 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]: """ - :returns: The credential_sid - :rtype: unicode + 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]: """ - return self._properties['credential_sid'] + 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. - @property - def binding_type(self): + :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: """ - :returns: The binding_type - :rtype: BindingInstance.BindingType + 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 """ - return self._properties['binding_type'] + 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, + } + ) - @property - def message_types(self): + headers = values.of({"Content-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: """ - :returns: The message_types - :rtype: unicode + 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 """ - return self._properties['message_types'] + 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, + } + ) - @property - def url(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + response = self._version.domain.twilio.request("GET", target_url) + return BindingPage(self._version, response, self._solution) - @property - def links(self): + async def get_page_async(self, target_url: str) -> BindingPage: """ - :returns: The links - :rtype: unicode + 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 """ - return self._properties['links'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return BindingPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> BindingContext: """ - Fetch a BindingInstance + Constructs a BindingContext - :returns: Fetched BindingInstance - :rtype: twilio.rest.chat.v2.service.binding.BindingInstance + :param sid: """ - return self._proxy.fetch() + return BindingContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def delete(self): + def __call__(self, sid: str) -> BindingContext: """ - Deletes the BindingInstance + Constructs a BindingContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: """ - return self._proxy.delete() + return BindingContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/ip_messaging/v2/service/channel/__init__.py b/twilio/rest/ip_messaging/v2/service/channel/__init__.py index a6111e31ab..8220a4be9c 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/__init__.py +++ b/twilio/rest/ip_messaging/v2/service/channel/__init__.py @@ -1,638 +1,962 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 ChannelList(ListResource): - """ """ - - def __init__(self, version, service_sid): - """ - Initialize the ChannelList - - :param Version version: Version that contains the resource - :param service_sid: The service_sid - - :returns: twilio.rest.chat.v2.service.channel.ChannelList - :rtype: twilio.rest.chat.v2.service.channel.ChannelList - """ - super(ChannelList, self).__init__(version) +class ChannelInstance(InstanceResource): - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Channels'.format(**self._solution) - - def create(self, friendly_name=values.unset, unique_name=values.unset, - attributes=values.unset, type=values.unset, - date_created=values.unset, date_updated=values.unset, - created_by=values.unset): - """ - Create a new ChannelInstance - - :param unicode friendly_name: The friendly_name - :param unicode unique_name: The unique_name - :param unicode attributes: The attributes - :param ChannelInstance.ChannelType type: The type - :param datetime date_created: The date_created - :param datetime date_updated: The date_updated - :param unicode created_by: The created_by - - :returns: Newly created ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.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, - }) + class ChannelType(object): + PUBLIC = "public" + PRIVATE = "private" - payload = self._version.create( - 'POST', - self._uri, - data=data, + 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") - return ChannelInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ChannelContext] = None - def stream(self, type=values.unset, limit=None, page_size=None): + @property + def _proxy(self) -> "ChannelContext": """ - 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. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param ChannelInstance.ChannelType type: The type - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.ChannelInstance] + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the ChannelInstance - page = self.page(type=type, page_size=limits['page_size'], ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - def list(self, type=values.unset, limit=None, page_size=None): + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Lists ChannelInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the ChannelInstance - :param ChannelInstance.ChannelType type: The type - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.ChannelInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(type=type, limit=limit, page_size=page_size, )) + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - def page(self, type=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch(self) -> "ChannelInstance": """ - Retrieve a single page of ChannelInstance records from the API. - Request is executed immediately + Fetch the ChannelInstance - :param ChannelInstance.ChannelType type: The type - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelPage + :returns: The fetched ChannelInstance """ - params = values.of({ - 'Type': serialize.map(type, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + async def fetch_async(self) -> "ChannelInstance": + """ + Asynchronous coroutine to fetch the ChannelInstance - return ChannelPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched ChannelInstance """ - Retrieve a specific page of ChannelInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_async() - :param str target_url: API-generated URL for the requested results page - - :returns: Page of ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelPage + 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": """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Update the ChannelInstance - return ChannelPage(self._version, response, self._solution) + :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: - def get(self, sid): + :returns: The updated ChannelInstance """ - Constructs a ChannelContext + 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, + ) - :param sid: The 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 + """ + 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, + ) - :returns: twilio.rest.chat.v2.service.channel.ChannelContext - :rtype: twilio.rest.chat.v2.service.channel.ChannelContext + @property + def invites(self) -> InviteList: """ - return ChannelContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Access the invites + """ + return self._proxy.invites - def __call__(self, sid): + @property + def members(self) -> MemberList: """ - Constructs a ChannelContext + Access the members + """ + return self._proxy.members - :param sid: The sid + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages - :returns: twilio.rest.chat.v2.service.channel.ChannelContext - :rtype: twilio.rest.chat.v2.service.channel.ChannelContext + @property + def webhooks(self) -> WebhookList: """ - return ChannelContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Access the webhooks + """ + return self._proxy.webhooks - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ChannelPage(Page): - """ """ +class ChannelContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the ChannelPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid + Initialize the ChannelContext - :returns: twilio.rest.chat.v2.service.channel.ChannelPage - :rtype: twilio.rest.chat.v2.service.channel.ChannelPage + :param version: Version that contains the resource + :param service_sid: + :param sid: """ - super(ChannelPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Build an instance of ChannelInstance + Deletes the ChannelInstance - :param dict payload: Payload response from the API + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: twilio.rest.chat.v2.service.channel.ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance + :returns: True if delete succeeds, False otherwise """ - return ChannelInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + 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) - def __repr__(self): + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the ChannelInstance - :returns: Machine friendly representation - :rtype: str + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + headers = values.of({}) -class ChannelContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, service_sid, sid): + def fetch(self) -> ChannelInstance: """ - Initialize the ChannelContext + Fetch the ChannelInstance - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: The sid - :returns: twilio.rest.chat.v2.service.channel.ChannelContext - :rtype: twilio.rest.chat.v2.service.channel.ChannelContext + :returns: The fetched ChannelInstance """ - super(ChannelContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Channels/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - # Dependents - self._members = None - self._messages = None - self._invites = None + 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"], + ) - def fetch(self): + async def fetch_async(self) -> ChannelInstance: """ - Fetch a ChannelInstance + Asynchronous coroutine to fetch the ChannelInstance - :returns: Fetched ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance + + :returns: The fetched ChannelInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + 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: """ - Deletes the ChannelInstance + Update the ChannelInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :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({}) - def update(self, friendly_name=values.unset, unique_name=values.unset, - attributes=values.unset, date_created=values.unset, - date_updated=values.unset, created_by=values.unset): - """ - Update the ChannelInstance + 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" - :param unicode friendly_name: The friendly_name - :param unicode unique_name: The unique_name - :param unicode attributes: The attributes - :param datetime date_created: The date_created - :param datetime date_updated: The date_updated - :param unicode created_by: The created_by - - :returns: Updated ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.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["Accept"] = "application/json" payload = self._version.update( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) return ChannelInstance( self._version, payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + 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 members(self): + def invites(self) -> InviteList: """ - Access the members + Access the invites + """ + if self._invites is None: + self._invites = InviteList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._invites - :returns: twilio.rest.chat.v2.service.channel.member.MemberList - :rtype: twilio.rest.chat.v2.service.channel.member.MemberList + @property + def members(self) -> MemberList: + """ + Access the members """ if self._members is None: self._members = MemberList( self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) return self._members @property - def messages(self): + def messages(self) -> MessageList: """ Access the messages - - :returns: twilio.rest.chat.v2.service.channel.message.MessageList - :rtype: twilio.rest.chat.v2.service.channel.message.MessageList """ if self._messages is None: self._messages = MessageList( self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) return self._messages @property - def invites(self): + def webhooks(self) -> WebhookList: """ - Access the invites - - :returns: twilio.rest.chat.v2.service.channel.invite.InviteList - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteList + Access the webhooks """ - if self._invites is None: - self._invites = InviteList( + if self._webhooks is None: + self._webhooks = WebhookList( self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) - return self._invites + return self._webhooks - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class ChannelInstance(InstanceResource): - """ """ - - class ChannelType(object): - PUBLIC = "public" - PRIVATE = "private" + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the ChannelInstance - - :returns: twilio.rest.chat.v2.service.channel.ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance - """ - super(ChannelInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'friendly_name': payload['friendly_name'], - 'unique_name': payload['unique_name'], - 'attributes': payload['attributes'], - 'type': payload['type'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'created_by': payload['created_by'], - 'members_count': deserialize.integer(payload['members_count']), - 'messages_count': deserialize.integer(payload['messages_count']), - 'url': payload['url'], - 'links': payload['links'], - } - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } +class ChannelPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of ChannelInstance - :returns: ChannelContext for this ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = ChannelContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] +class ChannelList(ListResource): - @property - def unique_name(self): + def __init__(self, version: Version, service_sid: str): """ - :returns: The unique_name - :rtype: unicode - """ - return self._properties['unique_name'] + Initialize the ChannelList - @property - def attributes(self): - """ - :returns: The attributes - :rtype: unicode - """ - return self._properties['attributes'] + :param version: Version that contains the resource + :param service_sid: - @property - def type(self): - """ - :returns: The type - :rtype: ChannelInstance.ChannelType """ - return self._properties['type'] + super().__init__(version) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + # 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", + } + ) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def created_by(self): - """ - :returns: The created_by - :rtype: unicode - """ - return self._properties['created_by'] + headers["Accept"] = "application/json" - @property - def members_count(self): - """ - :returns: The members_count - :rtype: unicode - """ - return self._properties['members_count'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def messages_count(self): + 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]: """ - :returns: The messages_count - :rtype: unicode + 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 """ - return self._properties['messages_count'] + limits = self._version.read_limits(limit, page_size) + page = self.page(type=type, page_size=limits["page_size"]) - @property - def url(self): + 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]: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(type=type, page_size=limits["page_size"]) - @property - def links(self): + 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]: """ - :returns: The links - :rtype: unicode + 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]: """ - return self._properties['links'] + 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 fetch(self): + 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: """ - Fetch a ChannelInstance + 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: Fetched ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance + :returns: Page of ChannelInstance """ - return self._proxy.fetch() + 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" - def delete(self): + 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: """ - Deletes the ChannelInstance + Asynchronously retrieve a single page of ChannelInstance records from the API. + Request is executed immediately - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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 """ - return self._proxy.delete() + 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"}) - def update(self, friendly_name=values.unset, unique_name=values.unset, - attributes=values.unset, date_created=values.unset, - date_updated=values.unset, created_by=values.unset): + 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: """ - Update the ChannelInstance + Retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately - :param unicode friendly_name: The friendly_name - :param unicode unique_name: The unique_name - :param unicode attributes: The attributes - :param datetime date_created: The date_created - :param datetime date_updated: The date_updated - :param unicode created_by: The created_by + :param target_url: API-generated URL for the requested results page - :returns: Updated ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance + :returns: Page of ChannelInstance """ - return self._proxy.update( - friendly_name=friendly_name, - unique_name=unique_name, - attributes=attributes, - date_created=date_created, - date_updated=date_updated, - created_by=created_by, - ) + response = self._version.domain.twilio.request("GET", target_url) + return ChannelPage(self._version, response, self._solution) - @property - def members(self): + async def get_page_async(self, target_url: str) -> ChannelPage: """ - Access the members + Asynchronously retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately - :returns: twilio.rest.chat.v2.service.channel.member.MemberList - :rtype: twilio.rest.chat.v2.service.channel.member.MemberList + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance """ - return self._proxy.members + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelPage(self._version, response, self._solution) - @property - def messages(self): + def get(self, sid: str) -> ChannelContext: """ - Access the messages + Constructs a ChannelContext - :returns: twilio.rest.chat.v2.service.channel.message.MessageList - :rtype: twilio.rest.chat.v2.service.channel.message.MessageList + :param sid: """ - return self._proxy.messages + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - @property - def invites(self): + def __call__(self, sid: str) -> ChannelContext: """ - Access the invites + Constructs a ChannelContext - :returns: twilio.rest.chat.v2.service.channel.invite.InviteList - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteList + :param sid: """ - return self._proxy.invites + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/ip_messaging/v2/service/channel/invite.py b/twilio/rest/ip_messaging/v2/service/channel/invite.py index 205135f511..4fa3c187fc 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/invite.py +++ b/twilio/rest/ip_messaging/v2/service/channel/invite.py @@ -1,462 +1,598 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 InviteList(ListResource): - """ """ +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 - def __init__(self, version, service_sid, channel_sid): + @property + def _proxy(self) -> "InviteContext": """ - Initialize the InviteList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param channel_sid: The channel_sid + :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 - :returns: twilio.rest.chat.v2.service.channel.invite.InviteList - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteList + def delete(self) -> bool: """ - super(InviteList, self).__init__(version) + Deletes the InviteInstance - # 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, role_sid=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create a new InviteInstance - - :param unicode identity: The identity - :param unicode role_sid: The role_sid + return self._proxy.delete() - :returns: Newly created InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteInstance + async def delete_async(self) -> bool: """ - data = values.of({'Identity': identity, 'RoleSid': role_sid, }) + Asynchronous coroutine that deletes the InviteInstance - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - return InviteInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - ) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def stream(self, identity=values.unset, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the InviteInstance - :param unicode identity: The identity - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.invite.InviteInstance] + :returns: The fetched InviteInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(identity=identity, page_size=limits['page_size'], ) + async def fetch_async(self) -> "InviteInstance": + """ + Asynchronous coroutine to fetch the InviteInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, identity=values.unset, limit=None, page_size=None): + :returns: The fetched 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 unicode identity: The identity - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + return await self._proxy.fetch_async() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.invite.InviteInstance] + def __repr__(self) -> str: """ - return list(self.stream(identity=identity, limit=limit, page_size=page_size, )) + Provide a friendly representation - def page(self, identity=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + :returns: Machine friendly representation """ - Retrieve a single page of InviteInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param unicode identity: The identity - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InvitePage +class InviteContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ - params = values.of({ - 'Identity': serialize.map(identity, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Initialize the InviteContext - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + :param sid: + """ + super().__init__(version) - return InvitePage(self._version, response, self._solution) + # 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 get_page(self, target_url): + def delete(self) -> bool: """ - Retrieve a specific page of InviteInstance records from the API. - Request is executed immediately + Deletes the InviteInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InvitePage + :returns: True if delete succeeds, False otherwise """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return InvitePage(self._version, response, self._solution) + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def get(self, sid): + async def delete_async(self) -> bool: """ - Constructs a InviteContext + Asynchronous coroutine that deletes the InviteInstance - :param sid: The sid - :returns: twilio.rest.chat.v2.service.channel.invite.InviteContext - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteContext + :returns: True if delete succeeds, False otherwise """ - return InviteContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers ) - def __call__(self, sid): + def fetch(self) -> InviteInstance: """ - Constructs a InviteContext + Fetch the InviteInstance - :param sid: The sid - :returns: twilio.rest.chat.v2.service.channel.invite.InviteContext - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteContext + :returns: The fetched InviteInstance """ - return InviteContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InviteInstance( self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + async def fetch_async(self) -> InviteInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the InviteInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched InviteInstance """ - return '' + headers = values.of({}) -class InvitePage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): - """ - Initialize the InvitePage + 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"], + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :param channel_sid: The channel_sid + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.chat.v2.service.channel.invite.InvitePage - :rtype: twilio.rest.chat.v2.service.channel.invite.InvitePage + :returns: Machine friendly representation """ - super(InvitePage, self).__init__(version, response) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Path Solution - self._solution = solution - def get_instance(self, payload): +class InvitePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: """ Build an instance of InviteInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.chat.v2.service.channel.invite.InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.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'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class InviteContext(InstanceContext): - """ """ +class InviteList(ListResource): - def __init__(self, version, service_sid, channel_sid, sid): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ - Initialize the InviteContext + Initialize the InviteList - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param channel_sid: The channel_sid - :param sid: The sid + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: - :returns: twilio.rest.chat.v2.service.channel.invite.InviteContext - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteContext """ - super(InviteContext, self).__init__(version) + 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) + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Invites".format( + **self._solution + ) - def fetch(self): + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: """ - Fetch a InviteInstance + Create the InviteInstance + + :param identity: + :param role_sid: - :returns: Fetched InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteInstance + :returns: The created InviteInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def delete(self): + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: """ - Deletes the InviteInstance + Asynchronously create the InviteInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :param identity: + :param role_sid: - def __repr__(self): + :returns: The created InviteInstance """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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" -class InviteInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - def __init__(self, version, payload, service_sid, channel_sid, sid=None): + 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]: """ - Initialize the 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: twilio.rest.chat.v2.service.channel.invite.InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteInstance + :returns: Generator that will yield up to limit results """ - super(InviteInstance, self).__init__(version) + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'channel_sid': payload['channel_sid'], - 'service_sid': payload['service_sid'], - 'identity': payload['identity'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'role_sid': payload['role_sid'], - 'created_by': payload['created_by'], - 'url': payload['url'], - } + return self._version.stream(page, limits["limit"]) - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], - } + 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. - @property - def _proxy(self): + :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 """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) - :returns: InviteContext for this InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteContext + 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]: """ - 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'], + 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, ) - return self._context + ) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: """ - return self._properties['sid'] + 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. - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + :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, + ) + ] - @property - def channel_sid(self): - """ - :returns: The channel_sid - :rtype: unicode + 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: """ - return self._properties['channel_sid'] + Retrieve a single page of InviteInstance records from the API. + Request is executed immediately - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] + :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 - @property - def identity(self): - """ - :returns: The identity - :rtype: unicode + :returns: Page of InviteInstance """ - return self._properties['identity'] + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Accept"] = "application/json" - @property - def role_sid(self): + 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: """ - :returns: The role_sid - :rtype: unicode + 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 """ - return self._properties['role_sid'] + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def created_by(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The created_by - :rtype: unicode + 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 """ - return self._properties['created_by'] + response = self._version.domain.twilio.request("GET", target_url) + return InvitePage(self._version, response, self._solution) - @property - def url(self): + async def get_page_async(self, target_url: str) -> InvitePage: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return InvitePage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> InviteContext: """ - Fetch a InviteInstance + Constructs a InviteContext - :returns: Fetched InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteInstance + :param sid: """ - return self._proxy.fetch() + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - def delete(self): + def __call__(self, sid: str) -> InviteContext: """ - Deletes the InviteInstance + Constructs a InviteContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: """ - return self._proxy.delete() + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/ip_messaging/v2/service/channel/member.py b/twilio/rest/ip_messaging/v2/service/channel/member.py index d79cd496cd..6456d3be20 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/member.py +++ b/twilio/rest/ip_messaging/v2/service/channel/member.py @@ -1,547 +1,905 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 MemberList(ListResource): - """ """ +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 - def __init__(self, version, service_sid, channel_sid): + @property + def _proxy(self) -> "MemberContext": """ - Initialize the MemberList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param channel_sid: The channel_sid + :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 - :returns: twilio.rest.chat.v2.service.channel.member.MemberList - :rtype: twilio.rest.chat.v2.service.channel.member.MemberList + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - super(MemberList, self).__init__(version) + Deletes the MemberInstance - # 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, role_sid=values.unset, - last_consumed_message_index=values.unset, - last_consumption_timestamp=values.unset, date_created=values.unset, - date_updated=values.unset): - """ - Create a new MemberInstance - - :param unicode identity: The identity - :param unicode role_sid: The role_sid - :param unicode last_consumed_message_index: The last_consumed_message_index - :param datetime last_consumption_timestamp: The last_consumption_timestamp - :param datetime date_created: The date_created - :param datetime date_updated: The date_updated - - :returns: Newly created MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.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), - }) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - payload = self._version.create( - 'POST', - self._uri, - data=data, + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) - return MemberInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], + 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 stream(self, identity=values.unset, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the MemberInstance - :param unicode identity: The identity - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.member.MemberInstance] + :returns: The fetched MemberInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(identity=identity, page_size=limits['page_size'], ) + async def fetch_async(self) -> "MemberInstance": + """ + Asynchronous coroutine to fetch the MemberInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, identity=values.unset, limit=None, page_size=None): + :returns: The fetched 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. + return await self._proxy.fetch_async() - :param unicode identity: The identity - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + 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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.member.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 list(self.stream(identity=identity, limit=limit, page_size=page_size, )) + 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 page(self, identity=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def __repr__(self) -> str: """ - Retrieve a single page of MemberInstance records from the API. - Request is executed immediately + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param unicode identity: The identity - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberPage +class MemberContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ - params = values.of({ - 'Identity': serialize.map(identity, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Initialize the MemberContext - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + :param sid: + """ + super().__init__(version) - return MemberPage(self._version, response, self._solution) + # 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 get_page(self, target_url): + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Retrieve a specific page of MemberInstance records from the API. - Request is executed immediately + Deletes the MemberInstance - :param str target_url: API-generated URL for the requested results page + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: Page of MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberPage + :returns: True if delete succeeds, False otherwise """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } ) - return MemberPage(self._version, response, self._solution) + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def get(self, sid): + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Constructs a MemberContext + Asynchronous coroutine that deletes the MemberInstance - :param sid: The sid + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: twilio.rest.chat.v2.service.channel.member.MemberContext - :rtype: twilio.rest.chat.v2.service.channel.member.MemberContext + :returns: True if delete succeeds, False otherwise """ - return MemberContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } ) - def __call__(self, sid): + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MemberInstance: """ - Constructs a MemberContext + Fetch the MemberInstance - :param sid: The sid - :returns: twilio.rest.chat.v2.service.channel.member.MemberContext - :rtype: twilio.rest.chat.v2.service.channel.member.MemberContext + :returns: The fetched MemberInstance """ - return MemberContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MemberInstance( self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + async def fetch_async(self) -> MemberInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the MemberInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched MemberInstance """ - return '' + headers = values.of({}) -class MemberPage(Page): - """ """ + 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 __init__(self, version, response, solution): + 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: """ - Initialize the MemberPage + 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"], + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :param channel_sid: The channel_sid + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.chat.v2.service.channel.member.MemberPage - :rtype: twilio.rest.chat.v2.service.channel.member.MemberPage + :returns: Machine friendly representation """ - super(MemberPage, self).__init__(version, response) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Path Solution - self._solution = solution - def get_instance(self, payload): +class MemberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: """ Build an instance of MemberInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.chat.v2.service.channel.member.MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.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'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class MemberContext(InstanceContext): - """ """ +class MemberList(ListResource): - def __init__(self, version, service_sid, channel_sid, sid): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ - Initialize the MemberContext + Initialize the MemberList - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param channel_sid: The channel_sid - :param sid: The sid + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: - :returns: twilio.rest.chat.v2.service.channel.member.MemberContext - :rtype: twilio.rest.chat.v2.service.channel.member.MemberContext """ - super(MemberContext, self).__init__(version) + 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) + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Members".format( + **self._solution + ) - def fetch(self): - """ - Fetch a MemberInstance + 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", + } + ) - :returns: Fetched MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberInstance - """ - params = values.of({}) + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def delete(self): - """ - Deletes the MemberInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def update(self, role_sid=values.unset, - last_consumed_message_index=values.unset, - last_consumption_timestamp=values.unset, date_created=values.unset, - date_updated=values.unset): - """ - Update the MemberInstance + 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", + } + ) - :param unicode role_sid: The role_sid - :param unicode last_consumed_message_index: The last_consumed_message_index - :param datetime last_consumption_timestamp: The last_consumption_timestamp - :param datetime date_created: The date_created - :param datetime date_updated: The date_updated + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: Updated MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.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), - }) + headers["Accept"] = "application/json" - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def __repr__(self): + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MemberInstance]: """ - Provide a friendly representation + 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. - :returns: Machine friendly representation - :rtype: str + :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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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"]) -class MemberInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, service_sid, channel_sid, sid=None): - """ - Initialize the MemberInstance - - :returns: twilio.rest.chat.v2.service.channel.member.MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberInstance - """ - super(MemberInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'channel_sid': payload['channel_sid'], - 'service_sid': payload['service_sid'], - 'identity': payload['identity'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'role_sid': payload['role_sid'], - 'last_consumed_message_index': deserialize.integer(payload['last_consumed_message_index']), - 'last_consumption_timestamp': deserialize.iso8601_datetime(payload['last_consumption_timestamp']), - 'url': payload['url'], - } + 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. - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], - } + :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) - @property - def _proxy(self): + :returns: Generator that will yield up to limit results """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) - :returns: MemberContext for this MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberContext + 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]: """ - 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'], + 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, ) - return self._context + ) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: """ - return self._properties['sid'] + 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. - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + :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, + ) + ] - @property - def channel_sid(self): + 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: """ - :returns: The channel_sid - :rtype: unicode - """ - return self._properties['channel_sid'] + Retrieve a single page of MemberInstance records from the API. + Request is executed immediately - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] + :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 - @property - def identity(self): - """ - :returns: The identity - :rtype: unicode + :returns: Page of MemberInstance """ - return self._properties['identity'] + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Accept"] = "application/json" - @property - def role_sid(self): - """ - :returns: The role_sid - :rtype: unicode - """ - return self._properties['role_sid'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, self._solution) - @property - def last_consumed_message_index(self): - """ - :returns: The last_consumed_message_index - :rtype: unicode + 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: """ - return self._properties['last_consumed_message_index'] + Asynchronously retrieve a single page of MemberInstance records from the API. + Request is executed immediately - @property - def last_consumption_timestamp(self): - """ - :returns: The last_consumption_timestamp - :rtype: datetime - """ - return self._properties['last_consumption_timestamp'] + :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 - @property - def url(self): + :returns: Page of MemberInstance """ - :returns: The url - :rtype: unicode + 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: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of MemberInstance """ - Fetch a MemberInstance + response = self._version.domain.twilio.request("GET", target_url) + return MemberPage(self._version, response, self._solution) - :returns: Fetched MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberInstance + async def get_page_async(self, target_url: str) -> MemberPage: """ - return self._proxy.fetch() + 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 - def delete(self): + :returns: Page of MemberInstance """ - Deletes the MemberInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return MemberPage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def get(self, sid: str) -> MemberContext: """ - return self._proxy.delete() + Constructs a MemberContext - def update(self, role_sid=values.unset, - last_consumed_message_index=values.unset, - last_consumption_timestamp=values.unset, date_created=values.unset, - date_updated=values.unset): + :param sid: """ - Update the MemberInstance + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - :param unicode role_sid: The role_sid - :param unicode last_consumed_message_index: The last_consumed_message_index - :param datetime last_consumption_timestamp: The last_consumption_timestamp - :param datetime date_created: The date_created - :param datetime date_updated: The date_updated + def __call__(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext - :returns: Updated MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberInstance + :param sid: """ - return self._proxy.update( - 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, + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/ip_messaging/v2/service/channel/message.py b/twilio/rest/ip_messaging/v2/service/channel/message.py index 8a396334ef..838b3c7271 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/message.py +++ b/twilio/rest/ip_messaging/v2/service/channel/message.py @@ -1,596 +1,905 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 MessageList(ListResource): - """ """ +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") - def __init__(self, version, service_sid, channel_sid): + 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": """ - Initialize the MessageList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param channel_sid: The channel_sid + :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 - :returns: twilio.rest.chat.v2.service.channel.message.MessageList - :rtype: twilio.rest.chat.v2.service.channel.message.MessageList + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - super(MessageList, self).__init__(version) + Deletes the MessageInstance - # 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, from_=values.unset, attributes=values.unset, - date_created=values.unset, date_updated=values.unset, - last_updated_by=values.unset, body=values.unset, - media_sid=values.unset): - """ - Create a new MessageInstance - - :param unicode from_: The from - :param unicode attributes: The attributes - :param datetime date_created: The date_created - :param datetime date_updated: The date_updated - :param unicode last_updated_by: The last_updated_by - :param unicode body: The body - :param unicode media_sid: The media_sid - - :returns: Newly created MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.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, - }) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - payload = self._version.create( - 'POST', - self._uri, - data=data, + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) - return MessageInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], + 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 stream(self, order=values.unset, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the MessageInstance - :param MessageInstance.OrderType order: The order - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.message.MessageInstance] + :returns: The fetched MessageInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(order=order, page_size=limits['page_size'], ) + async def fetch_async(self) -> "MessageInstance": + """ + Asynchronous coroutine to fetch the MessageInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, order=values.unset, limit=None, page_size=None): + :returns: The fetched 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. + return await self._proxy.fetch_async() - :param MessageInstance.OrderType order: The order - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + 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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.message.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 list(self.stream(order=order, limit=limit, page_size=page_size, )) + 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_, + ) - def page(self, order=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + 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: """ - Retrieve a single page of MessageInstance records from the API. - Request is executed immediately + Provide a friendly representation - :param MessageInstance.OrderType order: The order - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: Page of MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessagePage + +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: """ - params = values.of({ - 'Order': order, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + super().__init__(version) - response = self._version.page( - 'GET', - self._uri, - params=params, + # 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 + ) ) - return MessagePage(self._version, response, self._solution) - - def get_page(self, target_url): + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Retrieve a specific page of MessageInstance records from the API. - Request is executed immediately + Deletes the MessageInstance - :param str target_url: API-generated URL for the requested results page + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: Page of MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessagePage + :returns: True if delete succeeds, False otherwise """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } ) - return MessagePage(self._version, response, self._solution) + headers = values.of({}) - def get(self, sid): + 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: """ - Constructs a MessageContext + Asynchronous coroutine that deletes the MessageInstance - :param sid: The sid + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: twilio.rest.chat.v2.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v2.service.channel.message.MessageContext + :returns: True if delete succeeds, False otherwise """ - return MessageContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + 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 __call__(self, sid): + def fetch(self) -> MessageInstance: """ - Constructs a MessageContext + Fetch the MessageInstance - :param sid: The sid - :returns: twilio.rest.chat.v2.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v2.service.channel.message.MessageContext + :returns: The fetched MessageInstance """ - return MessageContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MessageInstance( self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + async def fetch_async(self) -> MessageInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the MessageInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched MessageInstance """ - return '' + headers = values.of({}) -class MessagePage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): + 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: """ - Initialize the MessagePage + Update the MessageInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :param channel_sid: The channel_sid + :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 - :returns: twilio.rest.chat.v2.service.channel.message.MessagePage - :rtype: twilio.rest.chat.v2.service.channel.message.MessagePage + 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: """ - super(MessagePage, self).__init__(version, response) + Provide a friendly representation - # Path Solution - self._solution = solution + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - def get_instance(self, payload): + +class MessagePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: """ Build an instance of MessageInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.chat.v2.service.channel.message.MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.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'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class MessageContext(InstanceContext): - """ """ +class MessageList(ListResource): - def __init__(self, version, service_sid, channel_sid, sid): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ - Initialize the MessageContext + Initialize the MessageList - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param channel_sid: The channel_sid - :param sid: The sid + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: - :returns: twilio.rest.chat.v2.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v2.service.channel.message.MessageContext """ - super(MessageContext, self).__init__(version) + 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) + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Messages".format( + **self._solution + ) - def fetch(self): - """ - Fetch a MessageInstance + 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", + } + ) - :returns: Fetched MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance - """ - params = values.of({}) + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def delete(self): - """ - Deletes the MessageInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def update(self, body=values.unset, attributes=values.unset, - date_created=values.unset, date_updated=values.unset, - last_updated_by=values.unset): - """ - Update the MessageInstance + 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", + } + ) - :param unicode body: The body - :param unicode attributes: The attributes - :param datetime date_created: The date_created - :param datetime date_updated: The date_updated - :param unicode last_updated_by: The last_updated_by + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: Updated MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance - """ - data = values.of({ - 'Body': body, - 'Attributes': attributes, - 'DateCreated': serialize.iso8601_datetime(date_created), - 'DateUpdated': serialize.iso8601_datetime(date_updated), - 'LastUpdatedBy': last_updated_by, - }) + headers["Accept"] = "application/json" - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def __repr__(self): + def stream( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: """ - Provide a friendly representation + 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. - :returns: Machine friendly representation - :rtype: str + :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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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"]) -class MessageInstance(InstanceResource): - """ """ + 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. - class OrderType(object): - ASC = "asc" - DESC = "desc" + :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) - def __init__(self, version, payload, service_sid, channel_sid, sid=None): - """ - Initialize the MessageInstance - - :returns: twilio.rest.chat.v2.service.channel.message.MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance - """ - super(MessageInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'attributes': payload['attributes'], - 'service_sid': payload['service_sid'], - 'to': payload['to'], - 'channel_sid': payload['channel_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'last_updated_by': payload['last_updated_by'], - 'was_edited': payload['was_edited'], - 'from_': payload['from'], - 'body': payload['body'], - 'index': deserialize.integer(payload['index']), - 'type': payload['type'], - 'media': payload['media'], - 'url': payload['url'], - } + :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"]) - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], - } + return self._version.stream_async(page, limits["limit"]) - @property - def _proxy(self): + def list( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: MessageContext for this MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageContext - """ - 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'], + :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, ) - return self._context + ) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + async def list_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: """ - return self._properties['sid'] + 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. - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + :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, + ) + ] - @property - def attributes(self): + 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: """ - :returns: The attributes - :rtype: unicode - """ - return self._properties['attributes'] + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] + :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 - @property - def to(self): - """ - :returns: The to - :rtype: unicode + :returns: Page of MessageInstance """ - return self._properties['to'] + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def channel_sid(self): - """ - :returns: The channel_sid - :rtype: unicode - """ - return self._properties['channel_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + headers["Accept"] = "application/json" - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) - @property - def last_updated_by(self): - """ - :returns: The last_updated_by - :rtype: unicode + 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: """ - return self._properties['last_updated_by'] + Asynchronously retrieve a single page of MessageInstance records from the API. + Request is executed immediately - @property - def was_edited(self): - """ - :returns: The was_edited - :rtype: bool - """ - return self._properties['was_edited'] + :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 - @property - def from_(self): - """ - :returns: The from - :rtype: unicode + :returns: Page of MessageInstance """ - return self._properties['from_'] + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def body(self): - """ - :returns: The body - :rtype: unicode - """ - return self._properties['body'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def index(self): - """ - :returns: The index - :rtype: unicode - """ - return self._properties['index'] + headers["Accept"] = "application/json" - @property - def type(self): - """ - :returns: The type - :rtype: unicode - """ - return self._properties['type'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) - @property - def media(self): + def get_page(self, target_url: str) -> MessagePage: """ - :returns: The media - :rtype: dict - """ - return self._properties['media'] + Retrieve a specific page of MessageInstance records from the API. + Request is executed immediately - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] + :param target_url: API-generated URL for the requested results page - def fetch(self): + :returns: Page of MessageInstance """ - Fetch a MessageInstance + response = self._version.domain.twilio.request("GET", target_url) + return MessagePage(self._version, response, self._solution) - :returns: Fetched MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance + async def get_page_async(self, target_url: str) -> MessagePage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of MessageInstance records from the API. + Request is executed immediately - def delete(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance """ - Deletes the MessageInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagePage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def get(self, sid: str) -> MessageContext: """ - return self._proxy.delete() + Constructs a MessageContext - def update(self, body=values.unset, attributes=values.unset, - date_created=values.unset, date_updated=values.unset, - last_updated_by=values.unset): + :param sid: """ - Update the MessageInstance + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - :param unicode body: The body - :param unicode attributes: The attributes - :param datetime date_created: The date_created - :param datetime date_updated: The date_updated - :param unicode last_updated_by: The last_updated_by + def __call__(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext - :returns: Updated MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance + :param sid: """ - return self._proxy.update( - body=body, - attributes=attributes, - date_created=date_created, - date_updated=date_updated, - last_updated_by=last_updated_by, + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 "".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 "".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 "" + + +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 "" diff --git a/twilio/rest/ip_messaging/v2/service/role.py b/twilio/rest/ip_messaging/v2/service/role.py index d4145d3a00..32f70c2272 100644 --- a/twilio/rest/ip_messaging/v2/service/role.py +++ b/twilio/rest/ip_messaging/v2/service/role.py @@ -1,460 +1,645 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 RoleList(ListResource): - """ """ +class RoleInstance(InstanceResource): - def __init__(self, version, service_sid): - """ - Initialize the RoleList + class RoleType(object): + CHANNEL = "channel" + DEPLOYMENT = "deployment" - :param Version version: Version that contains the resource - :param service_sid: The service_sid + """ + :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 - :returns: twilio.rest.chat.v2.service.role.RoleList - :rtype: twilio.rest.chat.v2.service.role.RoleList + @property + def _proxy(self) -> "RoleContext": """ - super(RoleList, self).__init__(version) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Roles'.format(**self._solution) + :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 create(self, friendly_name, type, permission): + def delete(self) -> bool: """ - Create a new RoleInstance + Deletes the RoleInstance - :param unicode friendly_name: The friendly_name - :param RoleInstance.RoleType type: The type - :param unicode permission: The permission - :returns: Newly created RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Type': type, - 'Permission': serialize.map(permission, lambda e: e), - }) + return self._proxy.delete() - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance - return RoleInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return await self._proxy.delete_async() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.role.RoleInstance] + def fetch(self) -> "RoleInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the RoleInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched RoleInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the RoleInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.role.RoleInstance] + :returns: The fetched RoleInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def update(self, permission: List[str]) -> "RoleInstance": """ - Retrieve a single page of RoleInstance records from the API. - Request is executed immediately + Update the RoleInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :param permission: - :returns: Page of RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RolePage + :returns: The updated RoleInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + return self._proxy.update( + permission=permission, ) - return RolePage(self._version, response, self._solution) - - def get_page(self, target_url): + async def update_async(self, permission: List[str]) -> "RoleInstance": """ - Retrieve a specific page of RoleInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the RoleInstance - :param str target_url: API-generated URL for the requested results page + :param permission: - :returns: Page of RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RolePage + :returns: The updated RoleInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + permission=permission, ) - return RolePage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a RoleContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - :param sid: The sid +class RoleContext(InstanceContext): - :returns: twilio.rest.chat.v2.service.role.RoleContext - :rtype: twilio.rest.chat.v2.service.role.RoleContext + def __init__(self, version: Version, service_sid: str, sid: str): """ - return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Initialize the RoleContext - def __call__(self, sid): + :param version: Version that contains the resource + :param service_sid: + :param sid: """ - Constructs a RoleContext + super().__init__(version) - :param sid: The sid + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Roles/{sid}".format(**self._solution) - :returns: twilio.rest.chat.v2.service.role.RoleContext - :rtype: twilio.rest.chat.v2.service.role.RoleContext + def delete(self) -> bool: """ - return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Deletes the RoleInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class RolePage(Page): - """ """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, response, solution): + async def delete_async(self) -> bool: """ - Initialize the RolePage + Asynchronous coroutine that deletes the RoleInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :returns: twilio.rest.chat.v2.service.role.RolePage - :rtype: twilio.rest.chat.v2.service.role.RolePage + :returns: True if delete succeeds, False otherwise """ - super(RolePage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: """ - Build an instance of RoleInstance + Fetch the RoleInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v2.service.role.RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance + :returns: The fetched RoleInstance """ - return RoleInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def __repr__(self): - """ - Provide a friendly representation + headers = values.of({}) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Accept"] = "application/json" + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) -class RoleContext(InstanceContext): - """ """ + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - def __init__(self, version, service_sid, sid): + async def fetch_async(self) -> RoleInstance: """ - Initialize the RoleContext + Asynchronous coroutine to fetch the RoleInstance - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: The sid - :returns: twilio.rest.chat.v2.service.role.RoleContext - :rtype: twilio.rest.chat.v2.service.role.RoleContext + :returns: The fetched RoleInstance """ - super(RoleContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Roles/{sid}'.format(**self._solution) + 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 fetch(self): + def update(self, permission: List[str]) -> RoleInstance: """ - Fetch a RoleInstance + Update the RoleInstance + + :param permission: - :returns: Fetched RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance + :returns: The updated RoleInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def update_async(self, permission: List[str]) -> RoleInstance: """ - Deletes the RoleInstance + Asynchronous coroutine to update the RoleInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :param permission: - def update(self, permission): + :returns: The updated RoleInstance """ - Update the RoleInstance - :param unicode permission: The permission + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) - :returns: Updated RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance - """ - data = values.of({'Permission': serialize.map(permission, lambda e: e), }) + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class RoleInstance(InstanceResource): - """ """ +class RolePage(Page): - class RoleType(object): - CHANNEL = "channel" - DEPLOYMENT = "deployment" + def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: + """ + Build an instance of RoleInstance - def __init__(self, version, payload, service_sid, sid=None): + :param payload: Payload response from the API """ - Initialize the RoleInstance + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - :returns: twilio.rest.chat.v2.service.role.RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance + def __repr__(self) -> str: """ - super(RoleInstance, self).__init__(version) + Provide a friendly representation - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'friendly_name': payload['friendly_name'], - 'type': payload['type'], - 'permissions': payload['permissions'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - } + :returns: Machine friendly representation + """ + return "" - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context +class RoleList(ListResource): - :returns: RoleContext for this RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleContext + def __init__(self, version: Version, service_sid: str): """ - if self._context is None: - self._context = RoleContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + Initialize the RoleList + + :param version: Version that contains the resource + :param service_sid: - @property - def sid(self): """ - :returns: The sid - :rtype: unicode + 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: """ - return self._properties['sid'] + Create the RoleInstance - @property - def account_sid(self): + :param friendly_name: + :param type: + :param permission: + + :returns: The created RoleInstance """ - :returns: The account_sid - :rtype: unicode + + 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: """ - return self._properties['account_sid'] + Asynchronously create the RoleInstance - @property - def service_sid(self): + :param friendly_name: + :param type: + :param permission: + + :returns: The created RoleInstance """ - :returns: The service_sid - :rtype: unicode + + 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]: """ - return self._properties['service_sid'] + 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. - @property - def friendly_name(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The friendly_name - :rtype: unicode + 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]: """ - return self._properties['friendly_name'] + 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. - @property - def type(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The type - :rtype: RoleInstance.RoleType + 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]: """ - return self._properties['type'] + Lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def permissions(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The permissions - :rtype: unicode + 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]: """ - return self._properties['permissions'] + 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. - @property - def date_created(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The date_created - :rtype: datetime + 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: """ - return self._properties['date_created'] + Retrieve a single page of RoleInstance records from the API. + Request is executed immediately - @property - def date_updated(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The date_updated - :rtype: datetime + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page of RoleInstance records from the API. + Request is executed immediately - @property - def url(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The url - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of RoleInstance """ - Fetch a RoleInstance + response = self._version.domain.twilio.request("GET", target_url) + return RolePage(self._version, response, self._solution) - :returns: Fetched RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance + async def get_page_async(self, target_url: str) -> RolePage: """ - return self._proxy.fetch() + 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 - def delete(self): + :returns: Page of RoleInstance """ - Deletes the RoleInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return RolePage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def get(self, sid: str) -> RoleContext: """ - return self._proxy.delete() + Constructs a RoleContext - def update(self, permission): + :param sid: """ - Update the RoleInstance + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - :param unicode permission: The permission + def __call__(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext - :returns: Updated RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance + :param sid: """ - return self._proxy.update(permission, ) + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/ip_messaging/v2/service/user/__init__.py b/twilio/rest/ip_messaging/v2/service/user/__init__.py index bd5acc2db6..f5f1454c72 100644 --- a/twilio/rest/ip_messaging/v2/service/user/__init__.py +++ b/twilio/rest/ip_messaging/v2/service/user/__init__.py @@ -1,567 +1,804 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 UserList(ListResource): - """ """ +class UserInstance(InstanceResource): - def __init__(self, version, service_sid): - """ - Initialize the UserList + 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") - :param Version version: Version that contains the resource - :param service_sid: The service_sid + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[UserContext] = None - :returns: twilio.rest.chat.v2.service.user.UserList - :rtype: twilio.rest.chat.v2.service.user.UserList + @property + def _proxy(self) -> "UserContext": """ - super(UserList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Users'.format(**self._solution) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def create(self, identity, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset): + :returns: UserContext for this UserInstance """ - Create a new UserInstance - - :param unicode identity: The identity - :param unicode role_sid: The role_sid - :param unicode attributes: The attributes - :param unicode friendly_name: The friendly_name + if self._context is None: + self._context = UserContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: Newly created UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserInstance + def delete(self) -> bool: """ - data = values.of({ - 'Identity': identity, - 'RoleSid': role_sid, - 'Attributes': attributes, - 'FriendlyName': friendly_name, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + Deletes the UserInstance - return UserInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.user.UserInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the UserInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the UserInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.user.UserInstance] + :returns: The fetched UserInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_async(self) -> "UserInstance": """ - Retrieve a single page of UserInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the UserInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserPage + :returns: The fetched UserInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_async() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return UserPage(self._version, response, self._solution) - - def get_page(self, target_url): + 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": """ - Retrieve a specific page of UserInstance records from the API. - Request is executed immediately + Update the UserInstance - :param str target_url: API-generated URL for the requested results page + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: - :returns: Page of UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserPage + :returns: The updated UserInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, ) - return UserPage(self._version, response, self._solution) + 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, + ) - def get(self, sid): + @property + def user_bindings(self) -> UserBindingList: """ - Constructs a UserContext - - :param sid: The sid - - :returns: twilio.rest.chat.v2.service.user.UserContext - :rtype: twilio.rest.chat.v2.service.user.UserContext + Access the user_bindings """ - return UserContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.user_bindings - def __call__(self, sid): + @property + def user_channels(self) -> UserChannelList: """ - Constructs a UserContext - - :param sid: The sid - - :returns: twilio.rest.chat.v2.service.user.UserContext - :rtype: twilio.rest.chat.v2.service.user.UserContext + Access the user_channels """ - return UserContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.user_channels - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class UserPage(Page): - """ """ +class UserContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the UserPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid + Initialize the UserContext - :returns: twilio.rest.chat.v2.service.user.UserPage - :rtype: twilio.rest.chat.v2.service.user.UserPage + :param version: Version that contains the resource + :param service_sid: + :param sid: """ - super(UserPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of UserInstance + Deletes the UserInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v2.service.user.UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserInstance + :returns: True if delete succeeds, False otherwise """ - return UserInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the UserInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class UserContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, service_sid, sid): + def fetch(self) -> UserInstance: """ - Initialize the UserContext + Fetch the UserInstance - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: The sid - :returns: twilio.rest.chat.v2.service.user.UserContext - :rtype: twilio.rest.chat.v2.service.user.UserContext + :returns: The fetched UserInstance """ - super(UserContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Users/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._user_channels = None - self._user_bindings = None + headers["Accept"] = "application/json" - def fetch(self): + 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: """ - Fetch a UserInstance + Asynchronous coroutine to fetch the UserInstance + - :returns: Fetched UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserInstance + :returns: The fetched UserInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + 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: """ - Deletes the UserInstance + Update the UserInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: - def update(self, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset): + :returns: The updated UserInstance """ - Update the UserInstance - :param unicode role_sid: The role_sid - :param unicode attributes: The attributes - :param unicode friendly_name: The friendly_name + 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" - :returns: Updated UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserInstance - """ - data = values.of({'RoleSid': role_sid, 'Attributes': attributes, 'FriendlyName': friendly_name, }) + headers["Accept"] = "application/json" payload = self._version.update( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) return UserInstance( self._version, payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - @property - def user_channels(self): + 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: """ - Access the user_channels + 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: twilio.rest.chat.v2.service.user.user_channel.UserChannelList - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelList + :returns: The updated UserInstance """ - if self._user_channels is None: - self._user_channels = UserChannelList( - self._version, - service_sid=self._solution['service_sid'], - user_sid=self._solution['sid'], + + 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 ) - return self._user_channels + ): + 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): + def user_bindings(self) -> UserBindingList: """ Access the user_bindings - - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingList - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingList """ if self._user_bindings is None: self._user_bindings = UserBindingList( self._version, - service_sid=self._solution['service_sid'], - user_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) return self._user_bindings - def __repr__(self): + @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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class UserInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the UserInstance - - :returns: twilio.rest.chat.v2.service.user.UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserInstance - """ - super(UserInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'attributes': payload['attributes'], - 'friendly_name': payload['friendly_name'], - 'role_sid': payload['role_sid'], - 'identity': payload['identity'], - 'is_online': payload['is_online'], - 'is_notifiable': payload['is_notifiable'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'joined_channels_count': deserialize.integer(payload['joined_channels_count']), - 'links': payload['links'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } +class UserPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> UserInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of UserInstance - :returns: UserContext for this UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = UserContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def sid(self): + def __repr__(self) -> str: """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] - @property - def attributes(self): - """ - :returns: The attributes - :rtype: unicode - """ - return self._properties['attributes'] +class UserList(ListResource): - @property - def friendly_name(self): + def __init__(self, version: Version, service_sid: str): """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] + Initialize the UserList - @property - def role_sid(self): - """ - :returns: The role_sid - :rtype: unicode - """ - return self._properties['role_sid'] + :param version: Version that contains the resource + :param service_sid: - @property - def identity(self): """ - :returns: The identity - :rtype: unicode - """ - return self._properties['identity'] + super().__init__(version) - @property - def is_online(self): - """ - :returns: The is_online - :rtype: bool - """ - return self._properties['is_online'] + # 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", + } + ) - @property - def is_notifiable(self): - """ - :returns: The is_notifiable - :rtype: bool - """ - return self._properties['is_notifiable'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def date_created(self): + 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]: """ - :returns: The date_created - :rtype: datetime + 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 """ - return self._properties['date_created'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def date_updated(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserInstance]: """ - :returns: The date_updated - :rtype: datetime + 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 """ - return self._properties['date_updated'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def joined_channels_count(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: """ - :returns: The joined_channels_count - :rtype: unicode + 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 self._properties['joined_channels_count'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def links(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: """ - :returns: The links - :rtype: unicode + 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 self._properties['links'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def url(self): + 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: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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) - def fetch(self): + 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: """ - Fetch a UserInstance + Asynchronously retrieve a single page of UserInstance records from the API. + Request is executed immediately - :returns: Fetched UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserInstance + :param page_token: PageToken provided by the API + :param page_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 """ - return self._proxy.fetch() + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" - def delete(self): + 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: """ - Deletes the UserInstance + Retrieve a specific page of UserInstance records from the API. + Request is executed immediately - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance """ - return self._proxy.delete() + response = self._version.domain.twilio.request("GET", target_url) + return UserPage(self._version, response, self._solution) - def update(self, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset): + async def get_page_async(self, target_url: str) -> UserPage: """ - Update the UserInstance + Asynchronously retrieve a specific page of UserInstance records from the API. + Request is executed immediately - :param unicode role_sid: The role_sid - :param unicode attributes: The attributes - :param unicode friendly_name: The friendly_name + :param target_url: API-generated URL for the requested results page - :returns: Updated UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserInstance + :returns: Page of UserInstance """ - return self._proxy.update(role_sid=role_sid, attributes=attributes, friendly_name=friendly_name, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserPage(self._version, response, self._solution) - @property - def user_channels(self): + def get(self, sid: str) -> UserContext: """ - Access the user_channels + Constructs a UserContext - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelList - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelList + :param sid: """ - return self._proxy.user_channels + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - @property - def user_bindings(self): + def __call__(self, sid: str) -> UserContext: """ - Access the user_bindings + Constructs a UserContext - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingList - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingList + :param sid: """ - return self._proxy.user_bindings + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/ip_messaging/v2/service/user/user_binding.py b/twilio/rest/ip_messaging/v2/service/user/user_binding.py index cfa607fa3a..4f1d9f10a7 100644 --- a/twilio/rest/ip_messaging/v2/service/user/user_binding.py +++ b/twilio/rest/ip_messaging/v2/service/user/user_binding.py @@ -1,460 +1,552 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 UserBindingList(ListResource): - """ """ - - def __init__(self, version, service_sid, user_sid): - """ - Initialize the UserBindingList +class UserBindingInstance(InstanceResource): - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param user_sid: The user_sid + class BindingType(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingList - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingList - """ - super(UserBindingList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'service_sid': service_sid, 'user_sid': user_sid, } - self._uri = '/Services/{service_sid}/Users/{user_sid}/Bindings'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "sid": sid or self.sid, + } + self._context: Optional[UserBindingContext] = None - def stream(self, binding_type=values.unset, limit=None, page_size=None): + @property + def _proxy(self) -> "UserBindingContext": """ - 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. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param UserBindingInstance.BindingType binding_type: The binding_type - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the UserBindingInstance - page = self.page(binding_type=binding_type, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, binding_type=values.unset, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists UserBindingInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the UserBindingInstance - :param UserBindingInstance.BindingType binding_type: The binding_type - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(binding_type=binding_type, limit=limit, page_size=page_size, )) + return await self._proxy.delete_async() - def page(self, binding_type=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch(self) -> "UserBindingInstance": """ - Retrieve a single page of UserBindingInstance records from the API. - Request is executed immediately + Fetch the UserBindingInstance - :param UserBindingInstance.BindingType binding_type: The binding_type - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of UserBindingInstance - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingPage + :returns: The fetched UserBindingInstance """ - params = values.of({ - 'BindingType': serialize.map(binding_type, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + async def fetch_async(self) -> "UserBindingInstance": + """ + Asynchronous coroutine to fetch the UserBindingInstance - return UserBindingPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched UserBindingInstance """ - Retrieve a specific page of UserBindingInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_async() - :param str target_url: API-generated URL for the requested results page + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of UserBindingInstance - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingPage + :returns: Machine friendly representation """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - return UserBindingPage(self._version, response, self._solution) - def get(self, sid): - """ - Constructs a UserBindingContext +class UserBindingContext(InstanceContext): - :param sid: The sid + def __init__(self, version: Version, service_sid: str, user_sid: str, sid: str): + """ + Initialize the UserBindingContext - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext + :param version: Version that contains the resource + :param service_sid: + :param user_sid: + :param sid: """ - return UserBindingContext( - self._version, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], - sid=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 __call__(self, sid): + def delete(self) -> bool: """ - Constructs a UserBindingContext + Deletes the UserBindingInstance - :param sid: The sid - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext + :returns: True if delete succeeds, False otherwise """ - return UserBindingContext( - self._version, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], - sid=sid, - ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the UserBindingInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class UserBindingPage(Page): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> UserBindingInstance: """ - Initialize the UserBindingPage + Fetch the UserBindingInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :param user_sid: The user_sid - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingPage - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingPage + :returns: The fetched UserBindingInstance """ - super(UserBindingPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): - """ - Build an instance of UserBindingInstance + headers["Accept"] = "application/json" - :param dict payload: Payload response from the API + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance - """ return UserBindingInstance( self._version, payload, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + async def fetch_async(self) -> UserBindingInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the UserBindingInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched UserBindingInstance """ - return '' + headers = values.of({}) -class UserBindingContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, service_sid, user_sid, sid): - """ - Initialize the UserBindingContext + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param user_sid: The user_sid - :param sid: The sid + return UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext + def __repr__(self) -> str: """ - super(UserBindingContext, self).__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) + Provide a friendly representation - def fetch(self): + :returns: Machine friendly representation """ - Fetch a UserBindingInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: Fetched UserBindingInstance - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance - """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) +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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], ) - def delete(self): - """ - Deletes the UserBindingInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" -class UserBindingInstance(InstanceResource): - """ """ +class UserBindingList(ListResource): - class BindingType(object): - GCM = "gcm" - APN = "apn" - FCM = "fcm" + def __init__(self, version: Version, service_sid: str, user_sid: str): + """ + Initialize the UserBindingList - def __init__(self, version, payload, service_sid, user_sid, sid=None): - """ - Initialize the UserBindingInstance - - :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance - """ - super(UserBindingInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'endpoint': payload['endpoint'], - 'identity': payload['identity'], - 'user_sid': payload['user_sid'], - 'credential_sid': payload['credential_sid'], - 'binding_type': payload['binding_type'], - 'message_types': payload['message_types'], - 'url': payload['url'], - } + :param version: Version that contains the resource + :param service_sid: + :param user_sid: + + """ + super().__init__(version) - # Context - self._context = None + # Path Solution self._solution = { - 'service_sid': service_sid, - 'user_sid': user_sid, - 'sid': sid or self._properties['sid'], + "service_sid": service_sid, + "user_sid": user_sid, } + self._uri = "/Services/{service_sid}/Users/{user_sid}/Bindings".format( + **self._solution + ) - @property - def _proxy(self): + def stream( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserBindingInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: UserBindingContext for this UserBindingInstance - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingContext - """ - 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 + :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) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['sid'] + limits = self._version.read_limits(limit, page_size) + page = self.page(binding_type=binding_type, page_size=limits["page_size"]) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + return self._version.stream(page, limits["limit"]) - @property - def service_sid(self): + 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]: """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] + 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. - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + :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) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime + :returns: Generator that will yield up to limit results """ - return self._properties['date_updated'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + binding_type=binding_type, page_size=limits["page_size"] + ) - @property - def endpoint(self): - """ - :returns: The endpoint - :rtype: unicode - """ - return self._properties['endpoint'] + return self._version.stream_async(page, limits["limit"]) - @property - def identity(self): + def list( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserBindingInstance]: """ - :returns: The identity - :rtype: unicode - """ - return self._properties['identity'] + Lists UserBindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def user_sid(self): - """ - :returns: The user_sid - :rtype: unicode - """ - return self._properties['user_sid'] + :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, + ) + ) - @property - def credential_sid(self): + 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]: """ - :returns: The credential_sid - :rtype: unicode + 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: """ - return self._properties['credential_sid'] + Retrieve a single page of UserBindingInstance records from the API. + Request is executed immediately - @property - def binding_type(self): + :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 """ - :returns: The binding_type - :rtype: UserBindingInstance.BindingType + 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 """ - return self._properties['binding_type'] + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def message_types(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The message_types - :rtype: unicode + 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 """ - return self._properties['message_types'] + response = self._version.domain.twilio.request("GET", target_url) + return UserBindingPage(self._version, response, self._solution) - @property - def url(self): + async def get_page_async(self, target_url: str) -> UserBindingPage: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserBindingPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> UserBindingContext: """ - Fetch a UserBindingInstance + Constructs a UserBindingContext - :returns: Fetched UserBindingInstance - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance + :param sid: """ - return self._proxy.fetch() + return UserBindingContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=sid, + ) - def delete(self): + def __call__(self, sid: str) -> UserBindingContext: """ - Deletes the UserBindingInstance + Constructs a UserBindingContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: """ - return self._proxy.delete() + return UserBindingContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/ip_messaging/v2/service/user/user_channel.py b/twilio/rest/ip_messaging/v2/service/user/user_channel.py index a17aa433dc..5cb544fc3f 100644 --- a/twilio/rest/ip_messaging/v2/service/user/user_channel.py +++ b/twilio/rest/ip_messaging/v2/service/user/user_channel.py @@ -1,277 +1,666 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 UserChannelList(ListResource): - """ """ +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 - def __init__(self, version, service_sid, user_sid): + @property + def _proxy(self) -> "UserChannelContext": """ - Initialize the UserChannelList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param user_sid: The sid + :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 - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelList - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelList + def delete(self) -> bool: """ - super(UserChannelList, self).__init__(version) + Deletes the UserChannelInstance - # 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=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + return self._proxy.delete() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserChannelInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance] + + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page(page_size=limits['page_size'], ) + def fetch(self) -> "UserChannelInstance": + """ + Fetch the UserChannelInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + return self._proxy.fetch() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + async def fetch_async(self) -> "UserChannelInstance": + """ + Asynchronous coroutine to fetch the UserChannelInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance] + + :returns: The fetched UserChannelInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + 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": """ - Retrieve a single page of UserChannelInstance records from the API. - Request is executed immediately + Update the UserChannelInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :param notification_level: + :param last_consumed_message_index: + :param last_consumption_timestamp: - :returns: Page of UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelPage + :returns: The updated UserChannelInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.update( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) - response = self._version.page( - 'GET', - self._uri, - params=params, + 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, ) - return UserChannelPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get_page(self, target_url): + :returns: Machine friendly representation """ - Retrieve a specific page of UserChannelInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param str target_url: API-generated URL for the requested results page - :returns: Page of UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelPage +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: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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 + ) ) - return UserChannelPage(self._version, response, self._solution) + def delete(self) -> bool: + """ + Deletes the UserChannelInstance + - def __repr__(self): + :returns: True if delete succeeds, False otherwise """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - return '' + Asynchronous coroutine that deletes the UserChannelInstance -class UserChannelPage(Page): - """ """ + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) - def __init__(self, version, response, solution): + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserChannelInstance: """ - Initialize the UserChannelPage + Fetch the UserChannelInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :param user_sid: The sid - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelPage - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelPage + :returns: The fetched UserChannelInstance """ - super(UserChannelPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): + 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: """ - Build an instance of UserChannelInstance + Asynchronous coroutine to fetch the UserChannelInstance + + + :returns: The fetched UserChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" - :param dict payload: Payload response from the API + 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: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance + :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'], + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], ) - def __repr__(self): + 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 - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class UserChannelInstance(InstanceResource): - """ """ +class UserChannelPage(Page): - class ChannelStatus(object): - JOINED = "joined" - INVITED = "invited" - NOT_PARTICIPATING = "not_participating" + 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 "" + + +class UserChannelList(ListResource): - def __init__(self, version, payload, service_sid, user_sid): + def __init__(self, version: Version, service_sid: str, user_sid: str): """ - Initialize the UserChannelInstance + Initialize the UserChannelList + + :param version: Version that contains the resource + :param service_sid: + :param user_sid: - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance """ - super(UserChannelInstance, self).__init__(version) + super().__init__(version) - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'channel_sid': payload['channel_sid'], - 'member_sid': payload['member_sid'], - 'status': payload['status'], - 'last_consumed_message_index': deserialize.integer(payload['last_consumed_message_index']), - 'unread_messages_count': deserialize.integer(payload['unread_messages_count']), - 'links': payload['links'], + # 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. - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'user_sid': user_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) - @property - def account_sid(self): + :returns: Generator that will yield up to limit results """ - :returns: The account_sid - :rtype: unicode + 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]: """ - return self._properties['account_sid'] + 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. - @property - def service_sid(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(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 """ - :returns: The service_sid - :rtype: unicode + 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]: """ - return self._properties['service_sid'] + 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. - @property - def channel_sid(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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: """ - :returns: The channel_sid - :rtype: unicode + 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 """ - return self._properties['channel_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def member_sid(self): + headers = values.of({"Content-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: """ - :returns: The member_sid - :rtype: unicode + 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 """ - return self._properties['member_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def status(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The status - :rtype: UserChannelInstance.ChannelStatus + 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 """ - return self._properties['status'] + response = self._version.domain.twilio.request("GET", target_url) + return UserChannelPage(self._version, response, self._solution) - @property - def last_consumed_message_index(self): + async def get_page_async(self, target_url: str) -> UserChannelPage: """ - :returns: The last_consumed_message_index - :rtype: unicode + 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 """ - return self._properties['last_consumed_message_index'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserChannelPage(self._version, response, self._solution) - @property - def unread_messages_count(self): + def get(self, channel_sid: str) -> UserChannelContext: """ - :returns: The unread_messages_count - :rtype: unicode + Constructs a UserChannelContext + + :param channel_sid: """ - return self._properties['unread_messages_count'] + return UserChannelContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=channel_sid, + ) - @property - def links(self): + def __call__(self, channel_sid: str) -> UserChannelContext: """ - :returns: The links - :rtype: unicode + Constructs a UserChannelContext + + :param channel_sid: """ - return self._properties['links'] + return UserChannelContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=channel_sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" 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 "" diff --git a/twilio/rest/lookups/__init__.py b/twilio/rest/lookups/__init__.py index c0cf6e3366..6a984f81ca 100644 --- a/twilio/rest/lookups/__init__.py +++ b/twilio/rest/lookups/__init__.py @@ -1,53 +1,15 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" +from warnings import warn -from twilio.base.domain import Domain -from twilio.rest.lookups.v1 import V1 +from twilio.rest.lookups.LookupsBase import LookupsBase +from twilio.rest.lookups.v1.phone_number import PhoneNumberList -class Lookups(Domain): - - def __init__(self, twilio): - """ - Initialize the Lookups Domain - - :returns: Domain for Lookups - :rtype: twilio.rest.lookups.Lookups - """ - super(Lookups, self).__init__(twilio) - - self.base_url = 'https://lookups.twilio.com' - - # Versions - self._v1 = None - +class Lookups(LookupsBase): @property - def v1(self): - """ - :returns: Version v1 of lookups - :rtype: twilio.rest.lookups.v1.V1 - """ - if self._v1 is None: - self._v1 = V1(self) - return self._v1 - - @property - def phone_numbers(self): - """ - :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberList - """ + def phone_numbers(self) -> PhoneNumberList: + warn( + "phone_numbers is deprecated. Use v1.phone_numbers instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v1.phone_numbers - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/lookups/v1/__init__.py b/twilio/rest/lookups/v1/__init__.py index 7ea2239cb2..72204da366 100644 --- a/twilio/rest/lookups/v1/__init__.py +++ b/twilio/rest/lookups/v1/__init__.py @@ -1,42 +1,43 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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): + def __init__(self, domain: Domain): """ Initialize the V1 version of Lookups - :returns: V1 version of Lookups - :rtype: twilio.rest.lookups.v1.V1.V1 + :param domain: The Twilio.lookups domain """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._phone_numbers = None + super().__init__(domain, "v1") + self._phone_numbers: Optional[PhoneNumberList] = None @property - def phone_numbers(self): - """ - :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberList - """ + def phone_numbers(self) -> PhoneNumberList: if self._phone_numbers is None: self._phone_numbers = PhoneNumberList(self) return self._phone_numbers - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/lookups/v1/phone_number.py b/twilio/rest/lookups/v1/phone_number.py index 379178d79b..304b89ab15 100644 --- a/twilio/rest/lookups/v1/phone_number.py +++ b/twilio/rest/lookups/v1/phone_number.py @@ -1,292 +1,272 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import serialize -from twilio.base import values +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.page import Page +from twilio.base.version import Version -class PhoneNumberList(ListResource): - """ """ +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 - def __init__(self, version): + @property + def _proxy(self) -> "PhoneNumberContext": """ - Initialize the PhoneNumberList - - :param Version version: Version that contains the resource + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: twilio.rest.lookups.v1.phone_number.PhoneNumberList - :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberList + :returns: PhoneNumberContext for this PhoneNumberInstance """ - super(PhoneNumberList, self).__init__(version) - - # Path Solution - self._solution = {} + if self._context is None: + self._context = PhoneNumberContext( + self._version, + phone_number=self._solution["phone_number"], + ) + return self._context - def get(self, phone_number): + 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": """ - Constructs a PhoneNumberContext + Fetch the PhoneNumberInstance - :param phone_number: The phone_number + :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: twilio.rest.lookups.v1.phone_number.PhoneNumberContext - :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberContext + :returns: The fetched PhoneNumberInstance """ - return PhoneNumberContext(self._version, phone_number=phone_number, ) + return self._proxy.fetch( + country_code=country_code, + type=type, + add_ons=add_ons, + add_ons_data=add_ons_data, + ) - def __call__(self, 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": """ - Constructs a PhoneNumberContext + Asynchronous coroutine to fetch the PhoneNumberInstance - :param phone_number: The phone_number + :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: twilio.rest.lookups.v1.phone_number.PhoneNumberContext - :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberContext + :returns: The fetched PhoneNumberInstance """ - return PhoneNumberContext(self._version, phone_number=phone_number, ) + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class PhoneNumberPage(Page): - """ """ +class PhoneNumberContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, phone_number: str): """ - Initialize the PhoneNumberPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the PhoneNumberContext - :returns: twilio.rest.lookups.v1.phone_number.PhoneNumberPage - :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberPage + :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(PhoneNumberPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of PhoneNumberInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.lookups.v1.phone_number.PhoneNumberInstance - :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberInstance - """ - return PhoneNumberInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation + self._solution = { + "phone_number": phone_number, + } + self._uri = "/PhoneNumbers/{phone_number}".format(**self._solution) - :returns: Machine friendly representation - :rtype: str + 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: """ - return '' + 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. -class PhoneNumberContext(InstanceContext): - """ """ - - def __init__(self, version, phone_number): + :returns: The fetched PhoneNumberInstance """ - Initialize the PhoneNumberContext - :param Version version: Version that contains the resource - :param phone_number: The phone_number - - :returns: twilio.rest.lookups.v1.phone_number.PhoneNumberContext - :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberContext - """ - super(PhoneNumberContext, self).__init__(version) + data = values.of( + { + "CountryCode": country_code, + "Type": serialize.map(type, lambda e: e), + "AddOns": serialize.map(add_ons, lambda e: e), + } + ) - # Path Solution - self._solution = {'phone_number': phone_number, } - self._uri = '/PhoneNumbers/{phone_number}'.format(**self._solution) + data.update(serialize.prefixed_collapsible_map(add_ons_data, "AddOns")) - def fetch(self, country_code=values.unset, type=values.unset, - add_ons=values.unset, add_ons_data=values.unset): - """ - Fetch a PhoneNumberInstance + headers = values.of({}) - :param unicode country_code: The country_code - :param unicode type: The type - :param unicode add_ons: The add_ons - :param dict add_ons_data: The add_ons_data + headers["Accept"] = "application/json" - :returns: Fetched PhoneNumberInstance - :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberInstance - """ - params = values.of({ - 'CountryCode': country_code, - 'Type': serialize.map(type, lambda e: e), - 'AddOns': serialize.map(add_ons, lambda e: e), - }) - - params.update(serialize.prefixed_collapsible_map(add_ons_data, 'AddOns')) payload = self._version.fetch( - 'GET', - self._uri, - params=params, + method="GET", uri=self._uri, params=data, headers=headers ) - return PhoneNumberInstance(self._version, payload, phone_number=self._solution['phone_number'], ) + return PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) - def __repr__(self): + 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: """ - Provide a friendly representation + Asynchronous coroutine to fetch the PhoneNumberInstance - :returns: Machine friendly representation - :rtype: str + :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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + data = values.of( + { + "CountryCode": country_code, + "Type": serialize.map(type, lambda e: e), + "AddOns": serialize.map(add_ons, lambda e: e), + } + ) -class PhoneNumberInstance(InstanceResource): - """ """ + data.update(serialize.prefixed_collapsible_map(add_ons_data, "AddOns")) - class Type(object): - LANDLINE = "landline" - MOBILE = "mobile" - VOIP = "voip" + headers = values.of({}) - def __init__(self, version, payload, phone_number=None): - """ - Initialize the PhoneNumberInstance + headers["Accept"] = "application/json" - :returns: twilio.rest.lookups.v1.phone_number.PhoneNumberInstance - :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberInstance - """ - super(PhoneNumberInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'caller_name': payload['caller_name'], - 'country_code': payload['country_code'], - 'phone_number': payload['phone_number'], - 'national_format': payload['national_format'], - 'carrier': payload['carrier'], - 'add_ons': payload['add_ons'], - 'url': payload['url'], - } + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) - # Context - self._context = None - self._solution = {'phone_number': phone_number or self._properties['phone_number'], } + return PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) - @property - def _proxy(self): + def __repr__(self) -> str: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Provide a friendly representation - :returns: PhoneNumberContext for this PhoneNumberInstance - :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberContext + :returns: Machine friendly representation """ - if self._context is None: - self._context = PhoneNumberContext(self._version, phone_number=self._solution['phone_number'], ) - return self._context + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def caller_name(self): - """ - :returns: The caller_name - :rtype: unicode - """ - return self._properties['caller_name'] - @property - def country_code(self): - """ - :returns: The country_code - :rtype: unicode - """ - return self._properties['country_code'] +class PhoneNumberList(ListResource): - @property - def phone_number(self): + def __init__(self, version: Version): """ - :returns: The phone_number - :rtype: unicode - """ - return self._properties['phone_number'] + Initialize the PhoneNumberList - @property - def national_format(self): - """ - :returns: The national_format - :rtype: unicode - """ - return self._properties['national_format'] + :param version: Version that contains the resource - @property - def carrier(self): """ - :returns: The carrier - :rtype: unicode - """ - return self._properties['carrier'] + super().__init__(version) - @property - def add_ons(self): - """ - :returns: The add_ons - :rtype: dict + def get(self, phone_number: str) -> PhoneNumberContext: """ - return self._properties['add_ons'] + Constructs a PhoneNumberContext - @property - def url(self): - """ - :returns: The url - :rtype: unicode + :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 self._properties['url'] + return PhoneNumberContext(self._version, phone_number=phone_number) - def fetch(self, country_code=values.unset, type=values.unset, - add_ons=values.unset, add_ons_data=values.unset): + def __call__(self, phone_number: str) -> PhoneNumberContext: """ - Fetch a PhoneNumberInstance - - :param unicode country_code: The country_code - :param unicode type: The type - :param unicode add_ons: The add_ons - :param dict add_ons_data: The add_ons_data + Constructs a PhoneNumberContext - :returns: Fetched PhoneNumberInstance - :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberInstance + :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 self._proxy.fetch( - country_code=country_code, - type=type, - add_ons=add_ons, - add_ons_data=add_ons_data, - ) + return PhoneNumberContext(self._version, phone_number=phone_number) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 "" 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 "".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 "".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 "" 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 "" 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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "" 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 "" + + +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 "" 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 "".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 "".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 "" 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 "" + + +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 "" 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 "" diff --git a/twilio/rest/messaging/__init__.py b/twilio/rest/messaging/__init__.py index aa5f3dbe6c..4e62832592 100644 --- a/twilio/rest/messaging/__init__.py +++ b/twilio/rest/messaging/__init__.py @@ -1,53 +1,99 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" +from warnings import warn -from twilio.base.domain import Domain -from twilio.rest.messaging.v1 import V1 +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(Domain): +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 - def __init__(self, twilio): - """ - Initialize the Messaging Domain + @property + def deactivations(self) -> DeactivationsList: + warn( + "deactivations is deprecated. Use v1.deactivations instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.deactivations - :returns: Domain for Messaging - :rtype: twilio.rest.messaging.Messaging - """ - super(Messaging, self).__init__(twilio) + @property + def domain_certs(self) -> DomainCertsList: + warn( + "domain_certs is deprecated. Use v1.domain_certs instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.domain_certs - self.base_url = 'https://messaging.twilio.com' + @property + def domain_config(self) -> DomainConfigList: + warn( + "domain_config is deprecated. Use v1.domain_config instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.domain_config - # Versions - self._v1 = None + @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 v1(self): - """ - :returns: Version v1 of messaging - :rtype: twilio.rest.messaging.v1.V1 - """ - if self._v1 is None: - self._v1 = V1(self) - return self._v1 + 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 services(self): - """ - :rtype: twilio.rest.messaging.v1.service.ServiceList - """ - return self.v1.services + 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 - def __repr__(self): - """ - Provide a friendly representation + @property + def services(self) -> ServiceList: + warn( + "services is deprecated. Use v1.services instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.services - :returns: Machine friendly representation - :rtype: str - """ - return '' + @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 index d816dfa667..6bd630fbd8 100644 --- a/twilio/rest/messaging/v1/__init__.py +++ b/twilio/rest/messaging/v1/__init__.py @@ -1,42 +1,151 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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): + def __init__(self, domain: Domain): """ Initialize the V1 version of Messaging - :returns: V1 version of Messaging - :rtype: twilio.rest.messaging.v1.V1.V1 + :param domain: The Twilio.messaging domain """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._services = None + 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 services(self): - """ - :rtype: twilio.rest.messaging.v1.service.ServiceList - """ + 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 - def __repr__(self): + @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 - :rtype: str """ - return '' + return "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "" + + +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 "" + + +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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" 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 "" + + +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 "" 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 "".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 "".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 "" 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 "".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 "".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 ( + "" + ) 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 "".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 "".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 "" diff --git a/twilio/rest/messaging/v1/service/__init__.py b/twilio/rest/messaging/v1/service/__init__.py index 49d9d08302..06a53c9a20 100644 --- a/twilio/rest/messaging/v1/service/__init__.py +++ b/twilio/rest/messaging/v1/service/__init__.py @@ -1,716 +1,1115 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 ServiceList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version): - """ - Initialize the ServiceList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.messaging.v1.service.ServiceList - :rtype: twilio.rest.messaging.v1.service.ServiceList - """ - super(ServiceList, self).__init__(version) +class ServiceInstance(InstanceResource): - # Path Solution - self._solution = {} - self._uri = '/Services'.format(**self._solution) - - def create(self, friendly_name, inbound_request_url=values.unset, - inbound_method=values.unset, fallback_url=values.unset, - fallback_method=values.unset, status_callback=values.unset, - sticky_sender=values.unset, mms_converter=values.unset, - smart_encoding=values.unset, scan_message_content=values.unset, - fallback_to_long_code=values.unset, area_code_geomatch=values.unset, - validity_period=values.unset, synchronous_validation=values.unset): - """ - Create a new ServiceInstance - - :param unicode friendly_name: The friendly_name - :param unicode inbound_request_url: The inbound_request_url - :param unicode inbound_method: The inbound_method - :param unicode fallback_url: The fallback_url - :param unicode fallback_method: The fallback_method - :param unicode status_callback: The status_callback - :param bool sticky_sender: The sticky_sender - :param bool mms_converter: The mms_converter - :param bool smart_encoding: The smart_encoding - :param ServiceInstance.ScanMessageContent scan_message_content: The scan_message_content - :param bool fallback_to_long_code: The fallback_to_long_code - :param bool area_code_geomatch: The area_code_geomatch - :param unicode validity_period: The validity_period - :param bool synchronous_validation: The synchronous_validation - - :returns: Newly created ServiceInstance - :rtype: twilio.rest.messaging.v1.service.ServiceInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'InboundRequestUrl': inbound_request_url, - 'InboundMethod': inbound_method, - 'FallbackUrl': fallback_url, - 'FallbackMethod': fallback_method, - 'StatusCallback': status_callback, - 'StickySender': sticky_sender, - 'MmsConverter': mms_converter, - 'SmartEncoding': smart_encoding, - 'ScanMessageContent': scan_message_content, - 'FallbackToLongCode': fallback_to_long_code, - 'AreaCodeGeomatch': area_code_geomatch, - 'ValidityPeriod': validity_period, - 'SynchronousValidation': synchronous_validation, - }) + class ScanMessageContent(object): + INHERIT = "inherit" + ENABLE = "enable" + DISABLE = "disable" - payload = self._version.create( - 'POST', - self._uri, - data=data, + """ + :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" ) - return ServiceInstance(self._version, payload, ) + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None - def stream(self, limit=None, page_size=None): + @property + def _proxy(self) -> "ServiceContext": """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.messaging.v1.service.ServiceInstance] + :returns: ServiceContext for this ServiceInstance """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def list(self, limit=None, page_size=None): + def delete(self) -> bool: """ - Lists ServiceInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the ServiceInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.messaging.v1.service.ServiceInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.delete() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def delete_async(self) -> bool: """ - Retrieve a single page of ServiceInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the ServiceInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of ServiceInstance - :rtype: twilio.rest.messaging.v1.service.ServicePage + :returns: True if delete succeeds, False otherwise """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.delete_async() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance - return ServicePage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched ServiceInstance """ - Retrieve a specific page of ServiceInstance records from the API. - Request is executed immediately + return self._proxy.fetch() - :param str target_url: API-generated URL for the requested results page + 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 - :returns: Page of ServiceInstance - :rtype: twilio.rest.messaging.v1.service.ServicePage + :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 """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, ) - return ServicePage(self._version, response, self._solution) + 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, + ) - def get(self, sid): + @property + def alpha_senders(self) -> AlphaSenderList: """ - Constructs a ServiceContext + Access the alpha_senders + """ + return self._proxy.alpha_senders - :param sid: The sid + @property + def channel_senders(self) -> ChannelSenderList: + """ + Access the channel_senders + """ + return self._proxy.channel_senders - :returns: twilio.rest.messaging.v1.service.ServiceContext - :rtype: twilio.rest.messaging.v1.service.ServiceContext + @property + def destination_alpha_senders(self) -> DestinationAlphaSenderList: """ - return ServiceContext(self._version, sid=sid, ) + Access the destination_alpha_senders + """ + return self._proxy.destination_alpha_senders - def __call__(self, sid): + @property + def phone_numbers(self) -> PhoneNumberList: """ - Constructs a ServiceContext + Access the phone_numbers + """ + return self._proxy.phone_numbers + + @property + def short_codes(self) -> ShortCodeList: + """ + Access the short_codes + """ + return self._proxy.short_codes - :param sid: The sid + @property + def us_app_to_person(self) -> UsAppToPersonList: + """ + Access the us_app_to_person + """ + return self._proxy.us_app_to_person - :returns: twilio.rest.messaging.v1.service.ServiceContext - :rtype: twilio.rest.messaging.v1.service.ServiceContext + @property + def us_app_to_person_usecases(self) -> UsAppToPersonUsecaseList: + """ + Access the us_app_to_person_usecases """ - return ServiceContext(self._version, sid=sid, ) + return self._proxy.us_app_to_person_usecases - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ServicePage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class ServiceContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the ServicePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the ServiceContext - :returns: twilio.rest.messaging.v1.service.ServicePage - :rtype: twilio.rest.messaging.v1.service.ServicePage + :param version: Version that contains the resource + :param sid: The SID of the Service resource to update. """ - super(ServicePage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of ServiceInstance + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) - :param dict payload: Payload response from the API + 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 - :returns: twilio.rest.messaging.v1.service.ServiceInstance - :rtype: twilio.rest.messaging.v1.service.ServiceInstance + def delete(self) -> bool: """ - return ServiceInstance(self._version, payload, ) + Deletes the ServiceInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class ServiceContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, sid): + async def delete_async(self) -> bool: """ - Initialize the ServiceContext + Asynchronous coroutine that deletes the ServiceInstance - :param Version version: Version that contains the resource - :param sid: The sid - :returns: twilio.rest.messaging.v1.service.ServiceContext - :rtype: twilio.rest.messaging.v1.service.ServiceContext - """ - super(ServiceContext, self).__init__(version) - - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Services/{sid}'.format(**self._solution) - - # Dependents - self._phone_numbers = None - self._short_codes = None - self._alpha_senders = None - - def update(self, friendly_name=values.unset, inbound_request_url=values.unset, - inbound_method=values.unset, fallback_url=values.unset, - fallback_method=values.unset, status_callback=values.unset, - sticky_sender=values.unset, mms_converter=values.unset, - smart_encoding=values.unset, scan_message_content=values.unset, - fallback_to_long_code=values.unset, area_code_geomatch=values.unset, - validity_period=values.unset, synchronous_validation=values.unset): + :returns: True if delete succeeds, False otherwise """ - Update the ServiceInstance - :param unicode friendly_name: The friendly_name - :param unicode inbound_request_url: The inbound_request_url - :param unicode inbound_method: The inbound_method - :param unicode fallback_url: The fallback_url - :param unicode fallback_method: The fallback_method - :param unicode status_callback: The status_callback - :param bool sticky_sender: The sticky_sender - :param bool mms_converter: The mms_converter - :param bool smart_encoding: The smart_encoding - :param ServiceInstance.ScanMessageContent scan_message_content: The scan_message_content - :param bool fallback_to_long_code: The fallback_to_long_code - :param bool area_code_geomatch: The area_code_geomatch - :param unicode validity_period: The validity_period - :param bool synchronous_validation: The synchronous_validation - - :returns: Updated ServiceInstance - :rtype: twilio.rest.messaging.v1.service.ServiceInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'InboundRequestUrl': inbound_request_url, - 'InboundMethod': inbound_method, - 'FallbackUrl': fallback_url, - 'FallbackMethod': fallback_method, - 'StatusCallback': status_callback, - 'StickySender': sticky_sender, - 'MmsConverter': mms_converter, - 'SmartEncoding': smart_encoding, - 'ScanMessageContent': scan_message_content, - 'FallbackToLongCode': fallback_to_long_code, - 'AreaCodeGeomatch': area_code_geomatch, - 'ValidityPeriod': validity_period, - 'SynchronousValidation': synchronous_validation, - }) + headers = values.of({}) - payload = self._version.update( - 'POST', - self._uri, - data=data, + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers ) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) - - def fetch(self): + def fetch(self) -> ServiceInstance: """ - Fetch a ServiceInstance + Fetch the ServiceInstance + - :returns: Fetched ServiceInstance - :rtype: twilio.rest.messaging.v1.service.ServiceInstance + :returns: The fetched ServiceInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) + headers = values.of({}) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" - def delete(self): - """ - Deletes the ServiceInstance + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - @property - def phone_numbers(self): + async def fetch_async(self) -> ServiceInstance: """ - Access the phone_numbers + Asynchronous coroutine to fetch the ServiceInstance - :returns: twilio.rest.messaging.v1.service.phone_number.PhoneNumberList - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberList - """ - if self._phone_numbers is None: - self._phone_numbers = PhoneNumberList(self._version, service_sid=self._solution['sid'], ) - return self._phone_numbers - @property - def short_codes(self): + :returns: The fetched ServiceInstance """ - Access the short_codes - :returns: twilio.rest.messaging.v1.service.short_code.ShortCodeList - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodeList - """ - if self._short_codes is None: - self._short_codes = ShortCodeList(self._version, service_sid=self._solution['sid'], ) - return self._short_codes + headers = values.of({}) - @property - def alpha_senders(self): - """ - Access the alpha_senders + headers["Accept"] = "application/json" - :returns: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderList - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderList - """ - if self._alpha_senders is None: - self._alpha_senders = AlphaSenderList(self._version, service_sid=self._solution['sid'], ) - return self._alpha_senders + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - def __repr__(self): - """ - Provide a friendly representation + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - :returns: Machine friendly representation - :rtype: str + 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: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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({}) -class ServiceInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - class ScanMessageContent(object): - INHERIT = "inherit" - ENABLE = "enable" - DISABLE = "disable" + headers["Accept"] = "application/json" - def __init__(self, version, payload, sid=None): - """ - Initialize the ServiceInstance - - :returns: twilio.rest.messaging.v1.service.ServiceInstance - :rtype: twilio.rest.messaging.v1.service.ServiceInstance - """ - super(ServiceInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'friendly_name': payload['friendly_name'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'inbound_request_url': payload['inbound_request_url'], - 'inbound_method': payload['inbound_method'], - 'fallback_url': payload['fallback_url'], - 'fallback_method': payload['fallback_method'], - 'status_callback': payload['status_callback'], - 'sticky_sender': payload['sticky_sender'], - 'mms_converter': payload['mms_converter'], - 'smart_encoding': payload['smart_encoding'], - 'scan_message_content': payload['scan_message_content'], - 'fallback_to_long_code': payload['fallback_to_long_code'], - 'area_code_geomatch': payload['area_code_geomatch'], - 'synchronous_validation': payload['synchronous_validation'], - 'validity_period': deserialize.integer(payload['validity_period']), - 'url': payload['url'], - 'links': payload['links'], - } + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + 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({}) - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: ServiceContext for this ServiceInstance - :rtype: twilio.rest.messaging.v1.service.ServiceContext - """ - if self._context is None: - self._context = ServiceContext(self._version, sid=self._solution['sid'], ) - return self._context + headers["Accept"] = "application/json" - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) @property - def friendly_name(self): + def alpha_senders(self) -> AlphaSenderList: """ - :returns: The friendly_name - :rtype: unicode + Access the alpha_senders """ - return self._properties['friendly_name'] + if self._alpha_senders is None: + self._alpha_senders = AlphaSenderList( + self._version, + self._solution["sid"], + ) + return self._alpha_senders @property - def date_created(self): + def channel_senders(self) -> ChannelSenderList: """ - :returns: The date_created - :rtype: datetime + Access the channel_senders """ - return self._properties['date_created'] + if self._channel_senders is None: + self._channel_senders = ChannelSenderList( + self._version, + self._solution["sid"], + ) + return self._channel_senders @property - def date_updated(self): + def destination_alpha_senders(self) -> DestinationAlphaSenderList: """ - :returns: The date_updated - :rtype: datetime + Access the destination_alpha_senders """ - return self._properties['date_updated'] + if self._destination_alpha_senders is None: + self._destination_alpha_senders = DestinationAlphaSenderList( + self._version, + self._solution["sid"], + ) + return self._destination_alpha_senders @property - def inbound_request_url(self): + def phone_numbers(self) -> PhoneNumberList: """ - :returns: The inbound_request_url - :rtype: unicode + Access the phone_numbers """ - return self._properties['inbound_request_url'] + if self._phone_numbers is None: + self._phone_numbers = PhoneNumberList( + self._version, + self._solution["sid"], + ) + return self._phone_numbers @property - def inbound_method(self): + def short_codes(self) -> ShortCodeList: """ - :returns: The inbound_method - :rtype: unicode + Access the short_codes """ - return self._properties['inbound_method'] + if self._short_codes is None: + self._short_codes = ShortCodeList( + self._version, + self._solution["sid"], + ) + return self._short_codes @property - def fallback_url(self): + def us_app_to_person(self) -> UsAppToPersonList: """ - :returns: The fallback_url - :rtype: unicode + Access the us_app_to_person """ - return self._properties['fallback_url'] + 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 fallback_method(self): + def us_app_to_person_usecases(self) -> UsAppToPersonUsecaseList: """ - :returns: The fallback_method - :rtype: unicode + Access the us_app_to_person_usecases """ - return self._properties['fallback_method'] + 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 - @property - def status_callback(self): - """ - :returns: The status_callback - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['status_callback'] + Provide a friendly representation - @property - def sticky_sender(self): - """ - :returns: The sticky_sender - :rtype: bool + :returns: Machine friendly representation """ - return self._properties['sticky_sender'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def mms_converter(self): - """ - :returns: The mms_converter - :rtype: bool - """ - return self._properties['mms_converter'] - @property - def smart_encoding(self): - """ - :returns: The smart_encoding - :rtype: bool - """ - return self._properties['smart_encoding'] +class ServicePage(Page): - @property - def scan_message_content(self): - """ - :returns: The scan_message_content - :rtype: ServiceInstance.ScanMessageContent + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: """ - return self._properties['scan_message_content'] + Build an instance of ServiceInstance - @property - def fallback_to_long_code(self): - """ - :returns: The fallback_to_long_code - :rtype: bool + :param payload: Payload response from the API """ - return self._properties['fallback_to_long_code'] + return ServiceInstance(self._version, payload) - @property - def area_code_geomatch(self): + def __repr__(self) -> str: """ - :returns: The area_code_geomatch - :rtype: bool + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['area_code_geomatch'] + return "" - @property - def synchronous_validation(self): + +class ServiceList(ListResource): + + def __init__(self, version: Version): """ - :returns: The synchronous_validation - :rtype: bool + 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]: """ - return self._properties['synchronous_validation'] + 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. - @property - def validity_period(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The validity_period - :rtype: unicode + 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]: """ - return self._properties['validity_period'] + 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. - @property - def url(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The url - :rtype: unicode + 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]: """ - return self._properties['url'] + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def links(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The links - :rtype: unicode + 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]: """ - return self._properties['links'] + 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. - def update(self, friendly_name=values.unset, inbound_request_url=values.unset, - inbound_method=values.unset, fallback_url=values.unset, - fallback_method=values.unset, status_callback=values.unset, - sticky_sender=values.unset, mms_converter=values.unset, - smart_encoding=values.unset, scan_message_content=values.unset, - fallback_to_long_code=values.unset, area_code_geomatch=values.unset, - validity_period=values.unset, synchronous_validation=values.unset): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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: """ - Update the ServiceInstance + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - :param unicode friendly_name: The friendly_name - :param unicode inbound_request_url: The inbound_request_url - :param unicode inbound_method: The inbound_method - :param unicode fallback_url: The fallback_url - :param unicode fallback_method: The fallback_method - :param unicode status_callback: The status_callback - :param bool sticky_sender: The sticky_sender - :param bool mms_converter: The mms_converter - :param bool smart_encoding: The smart_encoding - :param ServiceInstance.ScanMessageContent scan_message_content: The scan_message_content - :param bool fallback_to_long_code: The fallback_to_long_code - :param bool area_code_geomatch: The area_code_geomatch - :param unicode validity_period: The validity_period - :param bool synchronous_validation: The synchronous_validation - - :returns: Updated ServiceInstance - :rtype: twilio.rest.messaging.v1.service.ServiceInstance + :param page_token: PageToken provided by the API + :param page_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 """ - 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, + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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) - def fetch(self): + 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: """ - Fetch a ServiceInstance + 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: Fetched ServiceInstance - :rtype: twilio.rest.messaging.v1.service.ServiceInstance + :returns: Page of ServiceInstance """ - return self._proxy.fetch() + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - def delete(self): + headers = values.of({"Content-Type": "application/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: """ - Deletes the ServiceInstance + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance """ - return self._proxy.delete() + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) - @property - def phone_numbers(self): + async def get_page_async(self, target_url: str) -> ServicePage: """ - Access the phone_numbers + 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: twilio.rest.messaging.v1.service.phone_number.PhoneNumberList - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberList + :returns: Page of ServiceInstance """ - return self._proxy.phone_numbers + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) - @property - def short_codes(self): + def get(self, sid: str) -> ServiceContext: """ - Access the short_codes + Constructs a ServiceContext - :returns: twilio.rest.messaging.v1.service.short_code.ShortCodeList - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodeList + :param sid: The SID of the Service resource to update. """ - return self._proxy.short_codes + return ServiceContext(self._version, sid=sid) - @property - def alpha_senders(self): + def __call__(self, sid: str) -> ServiceContext: """ - Access the alpha_senders + Constructs a ServiceContext - :returns: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderList - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderList + :param sid: The SID of the Service resource to update. """ - return self._proxy.alpha_senders + return ServiceContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/messaging/v1/service/alpha_sender.py b/twilio/rest/messaging/v1/service/alpha_sender.py index e096bd81de..2ba4c2a45c 100644 --- a/twilio/rest/messaging/v1/service/alpha_sender.py +++ b/twilio/rest/messaging/v1/service/alpha_sender.py @@ -1,409 +1,542 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 AlphaSenderList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +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 - def __init__(self, version, service_sid): + @property + def _proxy(self) -> "AlphaSenderContext": """ - Initialize the AlphaSenderList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: The service_sid + :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 - :returns: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderList - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderList + def delete(self) -> bool: """ - super(AlphaSenderList, self).__init__(version) + Deletes the AlphaSenderInstance - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/AlphaSenders'.format(**self._solution) - def create(self, alpha_sender): + :returns: True if delete succeeds, False otherwise """ - Create a new AlphaSenderInstance - - :param unicode alpha_sender: The alpha_sender + return self._proxy.delete() - :returns: Newly created AlphaSenderInstance - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderInstance + async def delete_async(self) -> bool: """ - data = values.of({'AlphaSender': alpha_sender, }) + Asynchronous coroutine that deletes the AlphaSenderInstance - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - return AlphaSenderInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def stream(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the AlphaSenderInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderInstance] + :returns: The fetched AlphaSenderInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(page_size=limits['page_size'], ) + async def fetch_async(self) -> "AlphaSenderInstance": + """ + Asynchronous coroutine to fetch the AlphaSenderInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + return await self._proxy.fetch_async() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderInstance] + def __repr__(self) -> str: """ - return list(self.stream(limit=limit, page_size=page_size, )) + Provide a friendly representation - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + :returns: Machine friendly representation """ - Retrieve a single page of AlphaSenderInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of AlphaSenderInstance - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderPage +class AlphaSenderContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the AlphaSenderContext - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + :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) - return AlphaSenderPage(self._version, response, self._solution) + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/AlphaSenders/{sid}".format( + **self._solution + ) - def get_page(self, target_url): + def delete(self) -> bool: """ - Retrieve a specific page of AlphaSenderInstance records from the API. - Request is executed immediately + Deletes the AlphaSenderInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of AlphaSenderInstance - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderPage + :returns: True if delete succeeds, False otherwise """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return AlphaSenderPage(self._version, response, self._solution) + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def get(self, sid): + async def delete_async(self) -> bool: """ - Constructs a AlphaSenderContext + Asynchronous coroutine that deletes the AlphaSenderInstance - :param sid: The sid - :returns: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderContext - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderContext + :returns: True if delete succeeds, False otherwise """ - return AlphaSenderContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) - def __call__(self, sid): + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AlphaSenderInstance: """ - Constructs a AlphaSenderContext + Fetch the AlphaSenderInstance - :param sid: The sid - :returns: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderContext - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderContext + :returns: The fetched AlphaSenderInstance """ - return AlphaSenderContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) - def __repr__(self): + 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: """ - Provide a friendly representation + Asynchronous coroutine to fetch the AlphaSenderInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched AlphaSenderInstance """ - return '' + headers = values.of({}) -class AlphaSenderPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): - """ - Initialize the AlphaSenderPage + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid + return AlphaSenderInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderPage - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderPage + def __repr__(self) -> str: """ - super(AlphaSenderPage, self).__init__(version, response) + Provide a friendly representation - # Path Solution - self._solution = solution + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AlphaSenderPage(Page): - def get_instance(self, payload): + def get_instance(self, payload: Dict[str, Any]) -> AlphaSenderInstance: """ Build an instance of AlphaSenderInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderInstance - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderInstance + :param payload: Payload response from the API """ - return AlphaSenderInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + return AlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class AlphaSenderContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class AlphaSenderList(ListResource): - def __init__(self, version, service_sid, sid): + def __init__(self, version: Version, service_sid: str): """ - Initialize the AlphaSenderContext + Initialize the AlphaSenderList - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: The sid + :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. - :returns: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderContext - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderContext """ - super(AlphaSenderContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/AlphaSenders/{sid}'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/AlphaSenders".format(**self._solution) - def fetch(self): + def create(self, alpha_sender: str) -> AlphaSenderInstance: """ - Fetch a 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: Fetched AlphaSenderInstance - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderInstance + :returns: The created AlphaSenderInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], - sid=self._solution['sid'], + self._version, payload, service_sid=self._solution["service_sid"] ) - def delete(self): + async def create_async(self, alpha_sender: str) -> AlphaSenderInstance: """ - Deletes the AlphaSenderInstance + Asynchronously create the AlphaSenderInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :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. - def __repr__(self): + :returns: The created AlphaSenderInstance """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + data = values.of( + { + "AlphaSender": alpha_sender, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers["Content-Type"] = "application/x-www-form-urlencoded" -class AlphaSenderInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Accept"] = "application/json" - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the AlphaSenderInstance + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderInstance - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderInstance - """ - super(AlphaSenderInstance, self).__init__(version) + return AlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'alpha_sender': payload['alpha_sender'], - 'capabilities': payload['capabilities'], - 'url': payload['url'], - } + 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. - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['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) - @property - def _proxy(self): + :returns: Generator that will yield up to limit results """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - :returns: AlphaSenderContext for this AlphaSenderInstance - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderContext - """ - if self._context is None: - self._context = AlphaSenderContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + return self._version.stream(page, limits["limit"]) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AlphaSenderInstance]: """ - return self._properties['sid'] + 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. - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['account_sid'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def service_sid(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AlphaSenderInstance]: """ - :returns: The service_sid - :rtype: unicode + 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 self._properties['service_sid'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def date_created(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AlphaSenderInstance]: """ - :returns: The date_created - :rtype: datetime + 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 self._properties['date_created'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def date_updated(self): + 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: """ - :returns: The date_updated - :rtype: datetime + 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 """ - return self._properties['date_updated'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def alpha_sender(self): + headers = values.of({"Content-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: """ - :returns: The alpha_sender - :rtype: unicode + 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 """ - return self._properties['alpha_sender'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def capabilities(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The capabilities - :rtype: dict + 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 """ - return self._properties['capabilities'] + response = self._version.domain.twilio.request("GET", target_url) + return AlphaSenderPage(self._version, response, self._solution) - @property - def url(self): + async def get_page_async(self, target_url: str) -> AlphaSenderPage: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return AlphaSenderPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> AlphaSenderContext: """ - Fetch a AlphaSenderInstance + Constructs a AlphaSenderContext - :returns: Fetched AlphaSenderInstance - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderInstance + :param sid: The SID of the AlphaSender resource to fetch. """ - return self._proxy.fetch() + return AlphaSenderContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def delete(self): + def __call__(self, sid: str) -> AlphaSenderContext: """ - Deletes the AlphaSenderInstance + Constructs a AlphaSenderContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The SID of the AlphaSender resource to fetch. """ - return self._proxy.delete() + return AlphaSenderContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" diff --git a/twilio/rest/messaging/v1/service/phone_number.py b/twilio/rest/messaging/v1/service/phone_number.py index 01b1624b6f..11b806583e 100644 --- a/twilio/rest/messaging/v1/service/phone_number.py +++ b/twilio/rest/messaging/v1/service/phone_number.py @@ -1,418 +1,544 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 PhoneNumberList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +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 - def __init__(self, version, service_sid): + @property + def _proxy(self) -> "PhoneNumberContext": """ - Initialize the PhoneNumberList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: The service_sid + :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 - :returns: twilio.rest.messaging.v1.service.phone_number.PhoneNumberList - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberList + def delete(self) -> bool: """ - super(PhoneNumberList, self).__init__(version) + Deletes the PhoneNumberInstance - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/PhoneNumbers'.format(**self._solution) - def create(self, phone_number_sid): + :returns: True if delete succeeds, False otherwise """ - Create a new PhoneNumberInstance - - :param unicode phone_number_sid: The phone_number_sid + return self._proxy.delete() - :returns: Newly created PhoneNumberInstance - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberInstance + async def delete_async(self) -> bool: """ - data = values.of({'PhoneNumberSid': phone_number_sid, }) + Asynchronous coroutine that deletes the PhoneNumberInstance - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - return PhoneNumberInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def stream(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the PhoneNumberInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.messaging.v1.service.phone_number.PhoneNumberInstance] + :returns: The fetched PhoneNumberInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(page_size=limits['page_size'], ) + async def fetch_async(self) -> "PhoneNumberInstance": + """ + Asynchronous coroutine to fetch the PhoneNumberInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + return await self._proxy.fetch_async() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.messaging.v1.service.phone_number.PhoneNumberInstance] + def __repr__(self) -> str: """ - return list(self.stream(limit=limit, page_size=page_size, )) + Provide a friendly representation - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + :returns: Machine friendly representation """ - Retrieve a single page of PhoneNumberInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of PhoneNumberInstance - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberPage +class PhoneNumberContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the PhoneNumberContext - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + :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) - return PhoneNumberPage(self._version, response, self._solution) + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/PhoneNumbers/{sid}".format( + **self._solution + ) - def get_page(self, target_url): + def delete(self) -> bool: """ - Retrieve a specific page of PhoneNumberInstance records from the API. - Request is executed immediately + Deletes the PhoneNumberInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of PhoneNumberInstance - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberPage + :returns: True if delete succeeds, False otherwise """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return PhoneNumberPage(self._version, response, self._solution) + headers = values.of({}) - def get(self, sid): + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Constructs a PhoneNumberContext + Asynchronous coroutine that deletes the PhoneNumberInstance - :param sid: The sid - :returns: twilio.rest.messaging.v1.service.phone_number.PhoneNumberContext - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberContext + :returns: True if delete succeeds, False otherwise """ - return PhoneNumberContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) - def __call__(self, sid): + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> PhoneNumberInstance: """ - Constructs a PhoneNumberContext + Fetch the PhoneNumberInstance - :param sid: The sid - :returns: twilio.rest.messaging.v1.service.phone_number.PhoneNumberContext - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberContext + :returns: The fetched PhoneNumberInstance """ - return PhoneNumberContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) - def __repr__(self): + 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: """ - Provide a friendly representation + Asynchronous coroutine to fetch the PhoneNumberInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched PhoneNumberInstance """ - return '' + headers = values.of({}) -class PhoneNumberPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): - """ - Initialize the PhoneNumberPage + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid + return PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.messaging.v1.service.phone_number.PhoneNumberPage - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberPage + def __repr__(self) -> str: """ - super(PhoneNumberPage, self).__init__(version, response) + Provide a friendly representation - # Path Solution - self._solution = solution + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PhoneNumberPage(Page): - def get_instance(self, payload): + def get_instance(self, payload: Dict[str, Any]) -> PhoneNumberInstance: """ Build an instance of PhoneNumberInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.messaging.v1.service.phone_number.PhoneNumberInstance - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberInstance + :param payload: Payload response from the API """ - return PhoneNumberInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + return PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class PhoneNumberContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class PhoneNumberList(ListResource): - def __init__(self, version, service_sid, sid): + def __init__(self, version: Version, service_sid: str): """ - Initialize the PhoneNumberContext + Initialize the PhoneNumberList - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: The sid + :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. - :returns: twilio.rest.messaging.v1.service.phone_number.PhoneNumberContext - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberContext """ - super(PhoneNumberContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/PhoneNumbers/{sid}'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/PhoneNumbers".format(**self._solution) - def delete(self): + def create(self, phone_number_sid: str) -> PhoneNumberInstance: """ - Deletes the PhoneNumberInstance + Create the PhoneNumberInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :param phone_number_sid: The SID of the Phone Number being added to the Service. - def fetch(self): + :returns: The created PhoneNumberInstance """ - Fetch a PhoneNumberInstance - :returns: Fetched PhoneNumberInstance - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberInstance - """ - params = values.of({}) + data = values.of( + { + "PhoneNumberSid": phone_number_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], - sid=self._solution['sid'], + self._version, payload, service_sid=self._solution["service_sid"] ) - def __repr__(self): + async def create_async(self, phone_number_sid: str) -> PhoneNumberInstance: """ - Provide a friendly representation + Asynchronously create the PhoneNumberInstance - :returns: Machine friendly representation - :rtype: str + :param phone_number_sid: The SID of the Phone Number being added to the Service. + + :returns: The created PhoneNumberInstance """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + data = values.of( + { + "PhoneNumberSid": phone_number_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) -class PhoneNumberInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the PhoneNumberInstance + headers["Accept"] = "application/json" - :returns: twilio.rest.messaging.v1.service.phone_number.PhoneNumberInstance - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberInstance - """ - super(PhoneNumberInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'phone_number': payload['phone_number'], - 'country_code': payload['country_code'], - 'capabilities': payload['capabilities'], - 'url': payload['url'], - } + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + return PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def _proxy(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PhoneNumberInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: PhoneNumberContext for this PhoneNumberInstance - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberContext - """ - if self._context is None: - self._context = PhoneNumberContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['sid'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + return self._version.stream(page, limits["limit"]) - @property - def service_sid(self): + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PhoneNumberInstance]: """ - :returns: The service_sid - :rtype: unicode + 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 """ - return self._properties['service_sid'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def date_created(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PhoneNumberInstance]: """ - :returns: The date_created - :rtype: datetime + 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 self._properties['date_created'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def date_updated(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PhoneNumberInstance]: """ - :returns: The date_updated - :rtype: datetime + 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 self._properties['date_updated'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def phone_number(self): + 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: """ - :returns: The phone_number - :rtype: unicode + 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 """ - return self._properties['phone_number'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def country_code(self): + headers = values.of({"Content-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: """ - :returns: The country_code - :rtype: unicode + 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 """ - return self._properties['country_code'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def capabilities(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The capabilities - :rtype: unicode + 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 """ - return self._properties['capabilities'] + response = self._version.domain.twilio.request("GET", target_url) + return PhoneNumberPage(self._version, response, self._solution) - @property - def url(self): + async def get_page_async(self, target_url: str) -> PhoneNumberPage: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return PhoneNumberPage(self._version, response, self._solution) - def delete(self): + def get(self, sid: str) -> PhoneNumberContext: """ - Deletes the PhoneNumberInstance + Constructs a PhoneNumberContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The SID of the PhoneNumber resource to fetch. """ - return self._proxy.delete() + return PhoneNumberContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def fetch(self): + def __call__(self, sid: str) -> PhoneNumberContext: """ - Fetch a PhoneNumberInstance + Constructs a PhoneNumberContext - :returns: Fetched PhoneNumberInstance - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberInstance + :param sid: The SID of the PhoneNumber resource to fetch. """ - return self._proxy.fetch() + return PhoneNumberContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/messaging/v1/service/short_code.py b/twilio/rest/messaging/v1/service/short_code.py index 05cbbb7c8a..172c78dbb9 100644 --- a/twilio/rest/messaging/v1/service/short_code.py +++ b/twilio/rest/messaging/v1/service/short_code.py @@ -1,418 +1,542 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 ShortCodeList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +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 - def __init__(self, version, service_sid): + @property + def _proxy(self) -> "ShortCodeContext": """ - Initialize the ShortCodeList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: The service_sid + :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 - :returns: twilio.rest.messaging.v1.service.short_code.ShortCodeList - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodeList + def delete(self) -> bool: """ - super(ShortCodeList, self).__init__(version) + Deletes the ShortCodeInstance - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/ShortCodes'.format(**self._solution) - def create(self, short_code_sid): + :returns: True if delete succeeds, False otherwise """ - Create a new ShortCodeInstance - - :param unicode short_code_sid: The short_code_sid + return self._proxy.delete() - :returns: Newly created ShortCodeInstance - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodeInstance + async def delete_async(self) -> bool: """ - data = values.of({'ShortCodeSid': short_code_sid, }) + Asynchronous coroutine that deletes the ShortCodeInstance - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - return ShortCodeInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def stream(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the ShortCodeInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.messaging.v1.service.short_code.ShortCodeInstance] + :returns: The fetched ShortCodeInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(page_size=limits['page_size'], ) + async def fetch_async(self) -> "ShortCodeInstance": + """ + Asynchronous coroutine to fetch the ShortCodeInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + return await self._proxy.fetch_async() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.messaging.v1.service.short_code.ShortCodeInstance] + def __repr__(self) -> str: """ - return list(self.stream(limit=limit, page_size=page_size, )) + Provide a friendly representation - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + :returns: Machine friendly representation """ - Retrieve a single page of ShortCodeInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of ShortCodeInstance - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodePage +class ShortCodeContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the ShortCodeContext - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + :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) - return ShortCodePage(self._version, response, self._solution) + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/ShortCodes/{sid}".format(**self._solution) - def get_page(self, target_url): + def delete(self) -> bool: """ - Retrieve a specific page of ShortCodeInstance records from the API. - Request is executed immediately + Deletes the ShortCodeInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of ShortCodeInstance - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodePage + :returns: True if delete succeeds, False otherwise """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return ShortCodePage(self._version, response, self._solution) + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def get(self, sid): + async def delete_async(self) -> bool: """ - Constructs a ShortCodeContext + Asynchronous coroutine that deletes the ShortCodeInstance - :param sid: The sid - :returns: twilio.rest.messaging.v1.service.short_code.ShortCodeContext - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodeContext + :returns: True if delete succeeds, False otherwise """ - return ShortCodeContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) - def __call__(self, sid): + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ShortCodeInstance: """ - Constructs a ShortCodeContext + Fetch the ShortCodeInstance - :param sid: The sid - :returns: twilio.rest.messaging.v1.service.short_code.ShortCodeContext - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodeContext + :returns: The fetched ShortCodeInstance """ - return ShortCodeContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) - def __repr__(self): + 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: """ - Provide a friendly representation + Asynchronous coroutine to fetch the ShortCodeInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched ShortCodeInstance """ - return '' + headers = values.of({}) -class ShortCodePage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): - """ - Initialize the ShortCodePage + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid + return ShortCodeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.messaging.v1.service.short_code.ShortCodePage - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodePage + def __repr__(self) -> str: """ - super(ShortCodePage, self).__init__(version, response) + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Path Solution - self._solution = solution - def get_instance(self, payload): +class ShortCodePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ShortCodeInstance: """ Build an instance of ShortCodeInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.messaging.v1.service.short_code.ShortCodeInstance - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodeInstance + :param payload: Payload response from the API """ - return ShortCodeInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + return ShortCodeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class ShortCodeContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class ShortCodeList(ListResource): - def __init__(self, version, service_sid, sid): + def __init__(self, version: Version, service_sid: str): """ - Initialize the ShortCodeContext + Initialize the ShortCodeList - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: The sid + :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. - :returns: twilio.rest.messaging.v1.service.short_code.ShortCodeContext - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodeContext """ - super(ShortCodeContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/ShortCodes/{sid}'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/ShortCodes".format(**self._solution) - def delete(self): + def create(self, short_code_sid: str) -> ShortCodeInstance: """ - Deletes the ShortCodeInstance + Create the ShortCodeInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :param short_code_sid: The SID of the ShortCode resource being added to the Service. - def fetch(self): + :returns: The created ShortCodeInstance """ - Fetch a ShortCodeInstance - :returns: Fetched ShortCodeInstance - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodeInstance - """ - params = values.of({}) + 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" - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], - sid=self._solution['sid'], + self._version, payload, service_sid=self._solution["service_sid"] ) - def __repr__(self): + async def create_async(self, short_code_sid: str) -> ShortCodeInstance: """ - Provide a friendly representation + Asynchronously create the ShortCodeInstance - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + :param short_code_sid: The SID of the ShortCode resource being added to the Service. + :returns: The created ShortCodeInstance + """ -class ShortCodeInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + data = values.of( + { + "ShortCodeSid": short_code_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the ShortCodeInstance + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: twilio.rest.messaging.v1.service.short_code.ShortCodeInstance - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodeInstance - """ - super(ShortCodeInstance, self).__init__(version) + headers["Accept"] = "application/json" - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'short_code': payload['short_code'], - 'country_code': payload['country_code'], - 'capabilities': payload['capabilities'], - 'url': payload['url'], - } + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + return ShortCodeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def _proxy(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ShortCodeInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: ShortCodeContext for this ShortCodeInstance - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodeContext - """ - if self._context is None: - self._context = ShortCodeContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['sid'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + return self._version.stream(page, limits["limit"]) - @property - def service_sid(self): + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ShortCodeInstance]: """ - :returns: The service_sid - :rtype: unicode + 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 """ - return self._properties['service_sid'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def date_created(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ShortCodeInstance]: """ - :returns: The date_created - :rtype: datetime + 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 self._properties['date_created'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def date_updated(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ShortCodeInstance]: """ - :returns: The date_updated - :rtype: datetime + 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 self._properties['date_updated'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def short_code(self): + 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: """ - :returns: The short_code - :rtype: unicode + 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 """ - return self._properties['short_code'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def country_code(self): + headers = values.of({"Content-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: """ - :returns: The country_code - :rtype: unicode + 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 """ - return self._properties['country_code'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def capabilities(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The capabilities - :rtype: dict + 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 """ - return self._properties['capabilities'] + response = self._version.domain.twilio.request("GET", target_url) + return ShortCodePage(self._version, response, self._solution) - @property - def url(self): + async def get_page_async(self, target_url: str) -> ShortCodePage: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return ShortCodePage(self._version, response, self._solution) - def delete(self): + def get(self, sid: str) -> ShortCodeContext: """ - Deletes the ShortCodeInstance + Constructs a ShortCodeContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The SID of the ShortCode resource to fetch. """ - return self._proxy.delete() + return ShortCodeContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def fetch(self): + def __call__(self, sid: str) -> ShortCodeContext: """ - Fetch a ShortCodeInstance + Constructs a ShortCodeContext - :returns: Fetched ShortCodeInstance - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodeInstance + :param sid: The SID of the ShortCode resource to fetch. """ - return self._proxy.fetch() + return ShortCodeContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "" + + +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 "" 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 "" 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 "".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 "".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 "" + + +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 "" 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 "" diff --git a/twilio/rest/monitor/__init__.py b/twilio/rest/monitor/__init__.py index c686ca99d8..a39a5b248a 100644 --- a/twilio/rest/monitor/__init__.py +++ b/twilio/rest/monitor/__init__.py @@ -1,60 +1,25 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" +from warnings import warn -from twilio.base.domain import Domain -from twilio.rest.monitor.v1 import V1 +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(Domain): - - def __init__(self, twilio): - """ - Initialize the Monitor Domain - - :returns: Domain for Monitor - :rtype: twilio.rest.monitor.Monitor - """ - super(Monitor, self).__init__(twilio) - - self.base_url = 'https://monitor.twilio.com' - - # Versions - self._v1 = None - +class Monitor(MonitorBase): @property - def v1(self): - """ - :returns: Version v1 of monitor - :rtype: twilio.rest.monitor.v1.V1 - """ - if self._v1 is None: - self._v1 = V1(self) - return self._v1 - - @property - def alerts(self): - """ - :rtype: twilio.rest.monitor.v1.alert.AlertList - """ + def alerts(self) -> AlertList: + warn( + "alerts is deprecated. Use v1.alerts instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v1.alerts @property - def events(self): - """ - :rtype: twilio.rest.monitor.v1.event.EventList - """ + def events(self) -> EventList: + warn( + "events is deprecated. Use v1.events instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v1.events - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/monitor/v1/__init__.py b/twilio/rest/monitor/v1/__init__.py index efa1a5a36e..e892612b3b 100644 --- a/twilio/rest/monitor/v1/__init__.py +++ b/twilio/rest/monitor/v1/__init__.py @@ -1,53 +1,51 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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): + def __init__(self, domain: Domain): """ Initialize the V1 version of Monitor - :returns: V1 version of Monitor - :rtype: twilio.rest.monitor.v1.V1.V1 + :param domain: The Twilio.monitor domain """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._alerts = None - self._events = None + super().__init__(domain, "v1") + self._alerts: Optional[AlertList] = None + self._events: Optional[EventList] = None @property - def alerts(self): - """ - :rtype: twilio.rest.monitor.v1.alert.AlertList - """ + def alerts(self) -> AlertList: if self._alerts is None: self._alerts = AlertList(self) return self._alerts @property - def events(self): - """ - :rtype: twilio.rest.monitor.v1.event.EventList - """ + def events(self) -> EventList: if self._events is None: self._events = EventList(self) return self._events - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/monitor/v1/alert.py b/twilio/rest/monitor/v1/alert.py index 07b023aa30..829e633643 100644 --- a/twilio/rest/monitor/v1/alert.py +++ b/twilio/rest/monitor/v1/alert.py @@ -1,486 +1,501 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 AlertList(ListResource): - """ """ +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 - def __init__(self, version): + @property + def _proxy(self) -> "AlertContext": """ - Initialize the AlertList - - :param Version version: Version that contains the resource + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: twilio.rest.monitor.v1.alert.AlertList - :rtype: twilio.rest.monitor.v1.alert.AlertList + :returns: AlertContext for this AlertInstance """ - super(AlertList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Alerts'.format(**self._solution) + if self._context is None: + self._context = AlertContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def stream(self, log_level=values.unset, start_date=values.unset, - end_date=values.unset, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the AlertInstance - :param unicode log_level: The log_level - :param date start_date: The start_date - :param date end_date: The end_date - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.monitor.v1.alert.AlertInstance] + :returns: The fetched AlertInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page( - log_level=log_level, - start_date=start_date, - end_date=end_date, - page_size=limits['page_size'], - ) + async def fetch_async(self) -> "AlertInstance": + """ + Asynchronous coroutine to fetch the AlertInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, log_level=values.unset, start_date=values.unset, - end_date=values.unset, limit=None, page_size=None): + :returns: The fetched 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. + return await self._proxy.fetch_async() - :param unicode log_level: The log_level - :param date start_date: The start_date - :param date end_date: The end_date - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.monitor.v1.alert.AlertInstance] + def __repr__(self) -> str: """ - return list(self.stream( - log_level=log_level, - start_date=start_date, - end_date=end_date, - limit=limit, - page_size=page_size, - )) + Provide a friendly representation - def page(self, log_level=values.unset, start_date=values.unset, - end_date=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + :returns: Machine friendly representation """ - Retrieve a single page of AlertInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param unicode log_level: The log_level - :param date start_date: The start_date - :param date end_date: The end_date - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of AlertInstance - :rtype: twilio.rest.monitor.v1.alert.AlertPage +class AlertContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - params = values.of({ - 'LogLevel': log_level, - 'StartDate': serialize.iso8601_date(start_date), - 'EndDate': serialize.iso8601_date(end_date), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Initialize the AlertContext - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + :param version: Version that contains the resource + :param sid: The SID of the Alert resource to fetch. + """ + super().__init__(version) - return AlertPage(self._version, response, self._solution) + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Alerts/{sid}".format(**self._solution) - def get_page(self, target_url): + def fetch(self) -> AlertInstance: """ - Retrieve a specific page of AlertInstance records from the API. - Request is executed immediately + Fetch the AlertInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of AlertInstance - :rtype: twilio.rest.monitor.v1.alert.AlertPage + :returns: The fetched AlertInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return AlertPage(self._version, response, self._solution) + headers = values.of({}) - def get(self, sid): - """ - Constructs a AlertContext + headers["Accept"] = "application/json" - :param sid: The sid + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.monitor.v1.alert.AlertContext - :rtype: twilio.rest.monitor.v1.alert.AlertContext - """ - return AlertContext(self._version, sid=sid, ) + return AlertInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __call__(self, sid): + async def fetch_async(self) -> AlertInstance: """ - Constructs a AlertContext + Asynchronous coroutine to fetch the AlertInstance - :param sid: The sid - :returns: twilio.rest.monitor.v1.alert.AlertContext - :rtype: twilio.rest.monitor.v1.alert.AlertContext + :returns: The fetched AlertInstance """ - return AlertContext(self._version, sid=sid, ) - def __repr__(self): - """ - Provide a friendly representation + headers = values.of({}) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Accept"] = "application/json" + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) -class AlertPage(Page): - """ """ + return AlertInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __init__(self, version, response, solution): + def __repr__(self) -> str: """ - Initialize the AlertPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Provide a friendly representation - :returns: twilio.rest.monitor.v1.alert.AlertPage - :rtype: twilio.rest.monitor.v1.alert.AlertPage + :returns: Machine friendly representation """ - super(AlertPage, self).__init__(version, response) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Path Solution - self._solution = solution - def get_instance(self, payload): +class AlertPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AlertInstance: """ Build an instance of AlertInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.monitor.v1.alert.AlertInstance - :rtype: twilio.rest.monitor.v1.alert.AlertInstance + :param payload: Payload response from the API """ - return AlertInstance(self._version, payload, ) + return AlertInstance(self._version, payload) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class AlertContext(InstanceContext): - """ """ +class AlertList(ListResource): - def __init__(self, version, sid): + def __init__(self, version: Version): """ - Initialize the AlertContext + Initialize the AlertList - :param Version version: Version that contains the resource - :param sid: The sid + :param version: Version that contains the resource - :returns: twilio.rest.monitor.v1.alert.AlertContext - :rtype: twilio.rest.monitor.v1.alert.AlertContext """ - super(AlertContext, self).__init__(version) + super().__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Alerts/{sid}'.format(**self._solution) + self._uri = "/Alerts" - def fetch(self): + 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]: """ - Fetch a 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. - :returns: Fetched AlertInstance - :rtype: twilio.rest.monitor.v1.alert.AlertInstance - """ - params = values.of({}) + :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) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + :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 AlertInstance(self._version, payload, sid=self._solution['sid'], ) - - def delete(self): - """ - Deletes the AlertInstance + return self._version.stream(page, limits["limit"]) - :returns: True if delete succeeds, False otherwise - :rtype: bool + 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]: """ - return self._version.delete('delete', self._uri) + 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. - def __repr__(self): - """ - Provide a friendly representation + :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: Machine friendly representation - :rtype: str + :returns: Generator that will yield up to limit results """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class AlertInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, sid=None): - """ - Initialize the AlertInstance - - :returns: twilio.rest.monitor.v1.alert.AlertInstance - :rtype: twilio.rest.monitor.v1.alert.AlertInstance - """ - super(AlertInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'alert_text': payload['alert_text'], - 'api_version': payload['api_version'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_generated': deserialize.iso8601_datetime(payload['date_generated']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'error_code': payload['error_code'], - 'log_level': payload['log_level'], - 'more_info': payload['more_info'], - 'request_method': payload['request_method'], - 'request_url': payload['request_url'], - 'resource_sid': payload['resource_sid'], - 'sid': payload['sid'], - 'url': payload['url'], - 'request_variables': payload.get('request_variables'), - 'response_body': payload.get('response_body'), - 'response_headers': payload.get('response_headers'), - } + 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"], + ) - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + return self._version.stream_async(page, limits["limit"]) - @property - def _proxy(self): + 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]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Lists AlertInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: AlertContext for this AlertInstance - :rtype: twilio.rest.monitor.v1.alert.AlertContext - """ - if self._context is None: - self._context = AlertContext(self._version, sid=self._solution['sid'], ) - return self._context + :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, + ) + ) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + 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]: """ - return self._properties['account_sid'] + 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. - @property - def alert_text(self): + :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: """ - :returns: The alert_text - :rtype: unicode - """ - return self._properties['alert_text'] + Retrieve a single page of AlertInstance records from the API. + Request is executed immediately - @property - def api_version(self): - """ - :returns: The api_version - :rtype: unicode - """ - return self._properties['api_version'] + :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 - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime + :returns: Page of AlertInstance """ - return self._properties['date_created'] + 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, + } + ) - @property - def date_generated(self): - """ - :returns: The date_generated - :rtype: datetime - """ - return self._properties['date_generated'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Accept"] = "application/json" - @property - def error_code(self): - """ - :returns: The error_code - :rtype: unicode - """ - return self._properties['error_code'] + 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 - @property - def log_level(self): - """ - :returns: The log_level - :rtype: unicode - """ - return self._properties['log_level'] + :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 - @property - def more_info(self): - """ - :returns: The more_info - :rtype: unicode + :returns: Page of AlertInstance """ - return self._properties['more_info'] + 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, + } + ) - @property - def request_method(self): - """ - :returns: The request_method - :rtype: unicode - """ - return self._properties['request_method'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def request_url(self): - """ - :returns: The request_url - :rtype: unicode - """ - return self._properties['request_url'] + headers["Accept"] = "application/json" - @property - def request_variables(self): - """ - :returns: The request_variables - :rtype: unicode - """ - return self._properties['request_variables'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AlertPage(self._version, response) - @property - def resource_sid(self): + def get_page(self, target_url: str) -> AlertPage: """ - :returns: The resource_sid - :rtype: unicode - """ - return self._properties['resource_sid'] + Retrieve a specific page of AlertInstance records from the API. + Request is executed immediately - @property - def response_body(self): - """ - :returns: The response_body - :rtype: unicode - """ - return self._properties['response_body'] + :param target_url: API-generated URL for the requested results page - @property - def response_headers(self): - """ - :returns: The response_headers - :rtype: unicode + :returns: Page of AlertInstance """ - return self._properties['response_headers'] + response = self._version.domain.twilio.request("GET", target_url) + return AlertPage(self._version, response) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + async def get_page_async(self, target_url: str) -> AlertPage: """ - return self._properties['sid'] + Asynchronously retrieve a specific page of AlertInstance records from the API. + Request is executed immediately - @property - def url(self): - """ - :returns: The url - :rtype: unicode + :param target_url: API-generated URL for the requested results page + + :returns: Page of AlertInstance """ - return self._properties['url'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return AlertPage(self._version, response) - def fetch(self): + def get(self, sid: str) -> AlertContext: """ - Fetch a AlertInstance + Constructs a AlertContext - :returns: Fetched AlertInstance - :rtype: twilio.rest.monitor.v1.alert.AlertInstance + :param sid: The SID of the Alert resource to fetch. """ - return self._proxy.fetch() + return AlertContext(self._version, sid=sid) - def delete(self): + def __call__(self, sid: str) -> AlertContext: """ - Deletes the AlertInstance + Constructs a AlertContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The SID of the Alert resource to fetch. """ - return self._proxy.delete() + return AlertContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/monitor/v1/event.py b/twilio/rest/monitor/v1/event.py index b10f74aaa9..61450c872c 100644 --- a/twilio/rest/monitor/v1/event.py +++ b/twilio/rest/monitor/v1/event.py @@ -1,465 +1,541 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 EventList(ListResource): - """ """ +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 - def __init__(self, version): + @property + def _proxy(self) -> "EventContext": """ - Initialize the EventList - - :param Version version: Version that contains the resource + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: twilio.rest.monitor.v1.event.EventList - :rtype: twilio.rest.monitor.v1.event.EventList + :returns: EventContext for this EventInstance """ - super(EventList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Events'.format(**self._solution) + if self._context is None: + self._context = EventContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def stream(self, actor_sid=values.unset, event_type=values.unset, - resource_sid=values.unset, source_ip_address=values.unset, - start_date=values.unset, end_date=values.unset, limit=None, - page_size=None): + def fetch(self) -> "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. + Fetch the EventInstance - :param unicode actor_sid: The actor_sid - :param unicode event_type: The event_type - :param unicode resource_sid: The resource_sid - :param unicode source_ip_address: The source_ip_address - :param date start_date: The start_date - :param date end_date: The end_date - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.monitor.v1.event.EventInstance] + :returns: The fetched EventInstance """ - 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'], limits['page_limit']) + return self._proxy.fetch() - def list(self, actor_sid=values.unset, event_type=values.unset, - resource_sid=values.unset, source_ip_address=values.unset, - start_date=values.unset, end_date=values.unset, limit=None, - page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the EventInstance - :param unicode actor_sid: The actor_sid - :param unicode event_type: The event_type - :param unicode resource_sid: The resource_sid - :param unicode source_ip_address: The source_ip_address - :param date start_date: The start_date - :param date end_date: The end_date - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.monitor.v1.event.EventInstance] + :returns: The fetched EventInstance """ - 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, - )) + return await self._proxy.fetch_async() - def page(self, actor_sid=values.unset, event_type=values.unset, - resource_sid=values.unset, source_ip_address=values.unset, - start_date=values.unset, end_date=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def __repr__(self) -> str: """ - Retrieve a single page of EventInstance records from the API. - Request is executed immediately + Provide a friendly representation - :param unicode actor_sid: The actor_sid - :param unicode event_type: The event_type - :param unicode resource_sid: The resource_sid - :param unicode source_ip_address: The source_ip_address - :param date start_date: The start_date - :param date end_date: The end_date - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: Page of EventInstance - :rtype: twilio.rest.monitor.v1.event.EventPage - """ - params = values.of({ - 'ActorSid': actor_sid, - 'EventType': event_type, - 'ResourceSid': resource_sid, - 'SourceIpAddress': source_ip_address, - 'StartDate': serialize.iso8601_date(start_date), - 'EndDate': serialize.iso8601_date(end_date), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - response = self._version.page( - 'GET', - self._uri, - params=params, - ) +class EventContext(InstanceContext): - return EventPage(self._version, response, self._solution) + def __init__(self, version: Version, sid: str): + """ + Initialize the EventContext - def get_page(self, target_url): + :param version: Version that contains the resource + :param sid: The SID of the Event resource to fetch. """ - Retrieve a specific page of EventInstance records from the API. - Request is executed immediately + super().__init__(version) - :param str target_url: API-generated URL for the requested results page + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Events/{sid}".format(**self._solution) - :returns: Page of EventInstance - :rtype: twilio.rest.monitor.v1.event.EventPage + def fetch(self) -> EventInstance: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Fetch the EventInstance - return EventPage(self._version, response, self._solution) - def get(self, sid): + :returns: The fetched EventInstance """ - Constructs a EventContext - :param sid: The sid + headers = values.of({}) - :returns: twilio.rest.monitor.v1.event.EventContext - :rtype: twilio.rest.monitor.v1.event.EventContext - """ - return EventContext(self._version, sid=sid, ) + headers["Accept"] = "application/json" - def __call__(self, sid): - """ - Constructs a EventContext + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :param sid: The sid + return EventInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - :returns: twilio.rest.monitor.v1.event.EventContext - :rtype: twilio.rest.monitor.v1.event.EventContext + async def fetch_async(self) -> EventInstance: """ - return EventContext(self._version, sid=sid, ) + Asynchronous coroutine to fetch the EventInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: The fetched EventInstance """ - return '' + headers = values.of({}) -class EventPage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): - """ - Initialize the EventPage + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API + return EventInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - :returns: twilio.rest.monitor.v1.event.EventPage - :rtype: twilio.rest.monitor.v1.event.EventPage + def __repr__(self) -> str: """ - super(EventPage, self).__init__(version, response) + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Path Solution - self._solution = solution - def get_instance(self, payload): +class EventPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EventInstance: """ Build an instance of EventInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.monitor.v1.event.EventInstance - :rtype: twilio.rest.monitor.v1.event.EventInstance + :param payload: Payload response from the API """ - return EventInstance(self._version, payload, ) + return EventInstance(self._version, payload) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class EventContext(InstanceContext): - """ """ +class EventList(ListResource): - def __init__(self, version, sid): + def __init__(self, version: Version): """ - Initialize the EventContext + Initialize the EventList - :param Version version: Version that contains the resource - :param sid: The sid + :param version: Version that contains the resource - :returns: twilio.rest.monitor.v1.event.EventContext - :rtype: twilio.rest.monitor.v1.event.EventContext """ - super(EventContext, self).__init__(version) + super().__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Events/{sid}'.format(**self._solution) + self._uri = "/Events" - def fetch(self): + 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]: """ - Fetch a 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. - :returns: Fetched EventInstance - :rtype: twilio.rest.monitor.v1.event.EventInstance - """ - params = values.of({}) + :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) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + :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 EventInstance(self._version, payload, sid=self._solution['sid'], ) + 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. - def __repr__(self): - """ - Provide a friendly representation + :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: Machine friendly representation - :rtype: str + :returns: Generator that will yield up to limit results """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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"]) -class EventInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, sid=None): - """ - Initialize the EventInstance - - :returns: twilio.rest.monitor.v1.event.EventInstance - :rtype: twilio.rest.monitor.v1.event.EventInstance - """ - super(EventInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'actor_sid': payload['actor_sid'], - 'actor_type': payload['actor_type'], - 'description': payload['description'], - 'event_data': payload['event_data'], - 'event_date': deserialize.iso8601_datetime(payload['event_date']), - 'event_type': payload['event_type'], - 'resource_sid': payload['resource_sid'], - 'resource_type': payload['resource_type'], - 'sid': payload['sid'], - 'source': payload['source'], - 'source_ip_address': payload['source_ip_address'], - 'url': payload['url'], - 'links': payload['links'], - } + 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. - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + :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, + ) + ) - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: EventContext for this EventInstance - :rtype: twilio.rest.monitor.v1.event.EventContext + :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: """ - if self._context is None: - self._context = EventContext(self._version, sid=self._solution['sid'], ) - return self._context + Retrieve a single page of EventInstance records from the API. + Request is executed immediately - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + :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 - @property - def actor_sid(self): - """ - :returns: The actor_sid - :rtype: unicode + :returns: Page of EventInstance """ - return self._properties['actor_sid'] + 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, + } + ) - @property - def actor_type(self): - """ - :returns: The actor_type - :rtype: unicode - """ - return self._properties['actor_type'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def description(self): - """ - :returns: The description - :rtype: unicode - """ - return self._properties['description'] + headers["Accept"] = "application/json" - @property - def event_data(self): - """ - :returns: The event_data - :rtype: dict - """ - return self._properties['event_data'] + 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 - @property - def event_date(self): - """ - :returns: The event_date - :rtype: datetime - """ - return self._properties['event_date'] + :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 - @property - def event_type(self): - """ - :returns: The event_type - :rtype: unicode + :returns: Page of EventInstance """ - return self._properties['event_type'] + 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, + } + ) - @property - def resource_sid(self): - """ - :returns: The resource_sid - :rtype: unicode - """ - return self._properties['resource_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def resource_type(self): - """ - :returns: The resource_type - :rtype: unicode - """ - return self._properties['resource_type'] + headers["Accept"] = "application/json" - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventPage(self._version, response) - @property - def source(self): + def get_page(self, target_url: str) -> EventPage: """ - :returns: The source - :rtype: unicode - """ - return self._properties['source'] + Retrieve a specific page of EventInstance records from the API. + Request is executed immediately - @property - def source_ip_address(self): - """ - :returns: The source_ip_address - :rtype: unicode + :param target_url: API-generated URL for the requested results page + + :returns: Page of EventInstance """ - return self._properties['source_ip_address'] + response = self._version.domain.twilio.request("GET", target_url) + return EventPage(self._version, response) - @property - def url(self): + async def get_page_async(self, target_url: str) -> EventPage: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return EventPage(self._version, response) - @property - def links(self): + def get(self, sid: str) -> EventContext: """ - :returns: The links - :rtype: unicode + Constructs a EventContext + + :param sid: The SID of the Event resource to fetch. """ - return self._properties['links'] + return EventContext(self._version, sid=sid) - def fetch(self): + def __call__(self, sid: str) -> EventContext: """ - Fetch a EventInstance + Constructs a EventContext - :returns: Fetched EventInstance - :rtype: twilio.rest.monitor.v1.event.EventInstance + :param sid: The SID of the Event resource to fetch. """ - return self._proxy.fetch() + return EventContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 "" diff --git a/twilio/rest/notify/__init__.py b/twilio/rest/notify/__init__.py index 5dabaa6cb9..61f8fafb6b 100644 --- a/twilio/rest/notify/__init__.py +++ b/twilio/rest/notify/__init__.py @@ -1,60 +1,25 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" +from warnings import warn -from twilio.base.domain import Domain -from twilio.rest.notify.v1 import V1 +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(Domain): - - def __init__(self, twilio): - """ - Initialize the Notify Domain - - :returns: Domain for Notify - :rtype: twilio.rest.notify.Notify - """ - super(Notify, self).__init__(twilio) - - self.base_url = 'https://notify.twilio.com' - - # Versions - self._v1 = None - +class Notify(NotifyBase): @property - def v1(self): - """ - :returns: Version v1 of notify - :rtype: twilio.rest.notify.v1.V1 - """ - if self._v1 is None: - self._v1 = V1(self) - return self._v1 - - @property - def credentials(self): - """ - :rtype: twilio.rest.notify.v1.credential.CredentialList - """ + def credentials(self) -> CredentialList: + warn( + "credentials is deprecated. Use v1.credentials instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v1.credentials @property - def services(self): - """ - :rtype: twilio.rest.notify.v1.service.ServiceList - """ + def services(self) -> ServiceList: + warn( + "services is deprecated. Use v1.services instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v1.services - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/notify/v1/__init__.py b/twilio/rest/notify/v1/__init__.py index 20030334de..90cab95028 100644 --- a/twilio/rest/notify/v1/__init__.py +++ b/twilio/rest/notify/v1/__init__.py @@ -1,53 +1,51 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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): + def __init__(self, domain: Domain): """ Initialize the V1 version of Notify - :returns: V1 version of Notify - :rtype: twilio.rest.notify.v1.V1.V1 + :param domain: The Twilio.notify domain """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._credentials = None - self._services = None + super().__init__(domain, "v1") + self._credentials: Optional[CredentialList] = None + self._services: Optional[ServiceList] = None @property - def credentials(self): - """ - :rtype: twilio.rest.notify.v1.credential.CredentialList - """ + def credentials(self) -> CredentialList: if self._credentials is None: self._credentials = CredentialList(self) return self._credentials @property - def services(self): - """ - :rtype: twilio.rest.notify.v1.service.ServiceList - """ + def services(self) -> ServiceList: if self._services is None: self._services = ServiceList(self) return self._services - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/notify/v1/credential.py b/twilio/rest/notify/v1/credential.py index 969bff6731..9ca59927cb 100644 --- a/twilio/rest/notify/v1/credential.py +++ b/twilio/rest/notify/v1/credential.py @@ -1,476 +1,711 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 CredentialList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version): - """ - Initialize the CredentialList +class CredentialInstance(InstanceResource): - :param Version version: Version that contains the resource + class PushService(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" - :returns: twilio.rest.notify.v1.credential.CredentialList - :rtype: twilio.rest.notify.v1.credential.CredentialList - """ - super(CredentialList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {} - self._uri = '/Credentials'.format(**self._solution) + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CredentialContext] = None - def stream(self, limit=None, page_size=None): + @property + def _proxy(self) -> "CredentialContext": """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.notify.v1.credential.CredentialInstance] + :returns: CredentialContext for this CredentialInstance """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def list(self, limit=None, page_size=None): + def delete(self) -> bool: """ - Lists CredentialInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the CredentialInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.notify.v1.credential.CredentialInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.delete() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def delete_async(self) -> bool: """ - Retrieve a single page of CredentialInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the CredentialInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of CredentialInstance - :rtype: twilio.rest.notify.v1.credential.CredentialPage + :returns: True if delete succeeds, False otherwise """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + return await self._proxy.delete_async() - return CredentialPage(self._version, response, self._solution) - - def get_page(self, target_url): + def fetch(self) -> "CredentialInstance": """ - Retrieve a specific page of CredentialInstance records from the API. - Request is executed immediately + Fetch the CredentialInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of CredentialInstance - :rtype: twilio.rest.notify.v1.credential.CredentialPage + :returns: The fetched CredentialInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return CredentialPage(self._version, response, self._solution) + return self._proxy.fetch() - def create(self, type, friendly_name=values.unset, certificate=values.unset, - private_key=values.unset, sandbox=values.unset, api_key=values.unset, - secret=values.unset): + async def fetch_async(self) -> "CredentialInstance": """ - Create a new CredentialInstance + Asynchronous coroutine to fetch the CredentialInstance - :param CredentialInstance.PushService type: The type - :param unicode friendly_name: The friendly_name - :param unicode certificate: The certificate - :param unicode private_key: The private_key - :param bool sandbox: The sandbox - :param unicode api_key: The api_key - :param unicode secret: The secret - :returns: Newly created CredentialInstance - :rtype: twilio.rest.notify.v1.credential.CredentialInstance + :returns: The fetched CredentialInstance """ - data = values.of({ - 'Type': type, - 'FriendlyName': friendly_name, - 'Certificate': certificate, - 'PrivateKey': private_key, - 'Sandbox': sandbox, - 'ApiKey': api_key, - 'Secret': secret, - }) + return await self._proxy.fetch_async() - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return CredentialInstance(self._version, payload, ) - - def get(self, 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": """ - Constructs a CredentialContext + Update the CredentialInstance - :param sid: The sid + :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: twilio.rest.notify.v1.credential.CredentialContext - :rtype: twilio.rest.notify.v1.credential.CredentialContext + :returns: The updated CredentialInstance """ - return CredentialContext(self._version, sid=sid, ) + return self._proxy.update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - def __call__(self, 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": """ - Constructs a CredentialContext + Asynchronous coroutine to update the CredentialInstance - :param sid: The sid + :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: twilio.rest.notify.v1.credential.CredentialContext - :rtype: twilio.rest.notify.v1.credential.CredentialContext + :returns: The updated CredentialInstance """ - return CredentialContext(self._version, sid=sid, ) + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class CredentialPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class CredentialContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the CredentialPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the CredentialContext - :returns: twilio.rest.notify.v1.credential.CredentialPage - :rtype: twilio.rest.notify.v1.credential.CredentialPage + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. """ - super(CredentialPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) - def get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of CredentialInstance + Deletes the CredentialInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.notify.v1.credential.CredentialInstance - :rtype: twilio.rest.notify.v1.credential.CredentialInstance + :returns: True if delete succeeds, False otherwise """ - return CredentialInstance(self._version, payload, ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the CredentialInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class CredentialContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, sid): + def fetch(self) -> CredentialInstance: """ - Initialize the CredentialContext + Fetch the CredentialInstance - :param Version version: Version that contains the resource - :param sid: The sid - :returns: twilio.rest.notify.v1.credential.CredentialContext - :rtype: twilio.rest.notify.v1.credential.CredentialContext + :returns: The fetched CredentialInstance """ - super(CredentialContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Credentials/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialInstance: """ - Fetch a CredentialInstance + Asynchronous coroutine to fetch the CredentialInstance - :returns: Fetched CredentialInstance - :rtype: twilio.rest.notify.v1.credential.CredentialInstance + + :returns: The fetched CredentialInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], ) + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def update(self, friendly_name=values.unset, certificate=values.unset, - private_key=values.unset, sandbox=values.unset, api_key=values.unset, - secret=values.unset): + 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 unicode friendly_name: The friendly_name - :param unicode certificate: The certificate - :param unicode private_key: The private_key - :param bool sandbox: The sandbox - :param unicode api_key: The api_key - :param unicode secret: The secret - - :returns: Updated CredentialInstance - :rtype: twilio.rest.notify.v1.credential.CredentialInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Certificate': certificate, - 'PrivateKey': private_key, - 'Sandbox': sandbox, - 'ApiKey': api_key, - 'Secret': secret, - }) + :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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) - return CredentialInstance(self._version, payload, sid=self._solution['sid'], ) + 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({}) - def delete(self): - """ - Deletes the CredentialInstance + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + headers["Accept"] = "application/json" - def __repr__(self): + 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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class CredentialInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class CredentialPage(Page): - class PushService(object): - GCM = "gcm" - APN = "apn" - FCM = "fcm" + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: + """ + Build an instance of CredentialInstance - def __init__(self, version, payload, sid=None): + :param payload: Payload response from the API """ - Initialize the CredentialInstance + return CredentialInstance(self._version, payload) - :returns: twilio.rest.notify.v1.credential.CredentialInstance - :rtype: twilio.rest.notify.v1.credential.CredentialInstance + def __repr__(self) -> str: """ - super(CredentialInstance, self).__init__(version) + Provide a friendly representation - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'friendly_name': payload['friendly_name'], - 'type': payload['type'], - 'sandbox': payload['sandbox'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - } + :returns: Machine friendly representation + """ + return "" - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context +class CredentialList(ListResource): - :returns: CredentialContext for this CredentialInstance - :rtype: twilio.rest.notify.v1.credential.CredentialContext + def __init__(self, version: Version): """ - if self._context is None: - self._context = CredentialContext(self._version, sid=self._solution['sid'], ) - return self._context + Initialize the CredentialList + + :param version: Version that contains the resource - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode """ - return self._properties['sid'] + super().__init__(version) - @property - def account_sid(self): + 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: """ - :returns: The account_sid - :rtype: unicode + 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 """ - return self._properties['account_sid'] - @property - def friendly_name(self): + 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]: """ - :returns: The friendly_name - :rtype: unicode + 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 """ - return self._properties['friendly_name'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def type(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialInstance]: """ - :returns: The type - :rtype: CredentialInstance.PushService + 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 """ - return self._properties['type'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def sandbox(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: """ - :returns: The sandbox - :rtype: unicode + 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 self._properties['sandbox'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def date_created(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: """ - :returns: The date_created - :rtype: datetime + 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: """ - return self._properties['date_created'] + Retrieve a single page of CredentialInstance records from the API. + Request is executed immediately - @property - def date_updated(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The date_updated - :rtype: datetime + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page of CredentialInstance records from the API. + Request is executed immediately - @property - def url(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The url - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['url'] + Retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance """ - Fetch a CredentialInstance + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) - :returns: Fetched CredentialInstance - :rtype: twilio.rest.notify.v1.credential.CredentialInstance + async def get_page_async(self, target_url: str) -> CredentialPage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately - def update(self, friendly_name=values.unset, certificate=values.unset, - private_key=values.unset, sandbox=values.unset, api_key=values.unset, - secret=values.unset): + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance """ - Update the CredentialInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response) - :param unicode friendly_name: The friendly_name - :param unicode certificate: The certificate - :param unicode private_key: The private_key - :param bool sandbox: The sandbox - :param unicode api_key: The api_key - :param unicode secret: The secret + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext - :returns: Updated CredentialInstance - :rtype: twilio.rest.notify.v1.credential.CredentialInstance + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. """ - return self._proxy.update( - friendly_name=friendly_name, - certificate=certificate, - private_key=private_key, - sandbox=sandbox, - api_key=api_key, - secret=secret, - ) + return CredentialContext(self._version, sid=sid) - def delete(self): + def __call__(self, sid: str) -> CredentialContext: """ - Deletes the CredentialInstance + Constructs a CredentialContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. """ - return self._proxy.delete() + return CredentialContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/notify/v1/service/__init__.py b/twilio/rest/notify/v1/service/__init__.py index 6c96faf78a..e097e69a67 100644 --- a/twilio/rest/notify/v1/service/__init__.py +++ b/twilio/rest/notify/v1/service/__init__.py @@ -1,719 +1,948 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 -from twilio.rest.notify.v1.service.segment import SegmentList -from twilio.rest.notify.v1.service.user import UserList - - -class ServiceList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version): - """ - Initialize the ServiceList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.notify.v1.service.ServiceList - :rtype: twilio.rest.notify.v1.service.ServiceList - """ - super(ServiceList, self).__init__(version) - # Path Solution - self._solution = {} - self._uri = '/Services'.format(**self._solution) - - def create(self, friendly_name=values.unset, apn_credential_sid=values.unset, - gcm_credential_sid=values.unset, messaging_service_sid=values.unset, - facebook_messenger_page_id=values.unset, - default_apn_notification_protocol_version=values.unset, - default_gcm_notification_protocol_version=values.unset, - fcm_credential_sid=values.unset, - default_fcm_notification_protocol_version=values.unset, - log_enabled=values.unset, alexa_skill_id=values.unset, - default_alexa_notification_protocol_version=values.unset): - """ - Create a new ServiceInstance - - :param unicode friendly_name: The friendly_name - :param unicode apn_credential_sid: The apn_credential_sid - :param unicode gcm_credential_sid: The gcm_credential_sid - :param unicode messaging_service_sid: The messaging_service_sid - :param unicode facebook_messenger_page_id: The facebook_messenger_page_id - :param unicode default_apn_notification_protocol_version: The default_apn_notification_protocol_version - :param unicode default_gcm_notification_protocol_version: The default_gcm_notification_protocol_version - :param unicode fcm_credential_sid: The fcm_credential_sid - :param unicode default_fcm_notification_protocol_version: The default_fcm_notification_protocol_version - :param bool log_enabled: The log_enabled - :param unicode alexa_skill_id: The alexa_skill_id - :param unicode default_alexa_notification_protocol_version: The default_alexa_notification_protocol_version - - :returns: Newly created ServiceInstance - :rtype: twilio.rest.notify.v1.service.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': log_enabled, - 'AlexaSkillId': alexa_skill_id, - 'DefaultAlexaNotificationProtocolVersion': default_alexa_notification_protocol_version, - }) - payload = self._version.create( - 'POST', - self._uri, - data=data, +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" ) - return ServiceInstance(self._version, payload, ) + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None - def stream(self, friendly_name=values.unset, limit=None, page_size=None): + @property + def _proxy(self) -> "ServiceContext": """ - 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. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param unicode friendly_name: The friendly_name - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.notify.v1.service.ServiceInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the ServiceInstance - page = self.page(friendly_name=friendly_name, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, friendly_name=values.unset, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists ServiceInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the ServiceInstance - :param unicode friendly_name: The friendly_name - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.notify.v1.service.ServiceInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(friendly_name=friendly_name, limit=limit, page_size=page_size, )) + return await self._proxy.delete_async() - def page(self, friendly_name=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch(self) -> "ServiceInstance": """ - Retrieve a single page of ServiceInstance records from the API. - Request is executed immediately + Fetch the ServiceInstance - :param unicode friendly_name: The friendly_name - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of ServiceInstance - :rtype: twilio.rest.notify.v1.service.ServicePage + :returns: The fetched ServiceInstance """ - params = values.of({ - 'FriendlyName': friendly_name, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance - return ServicePage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched ServiceInstance """ - Retrieve a specific page of ServiceInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_async() - :param str target_url: API-generated URL for the requested results page + 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 - :returns: Page of ServiceInstance - :rtype: twilio.rest.notify.v1.service.ServicePage + :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 """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, ) - return ServicePage(self._version, response, self._solution) + 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, + ) - def get(self, sid): + @property + def bindings(self) -> BindingList: """ - Constructs a ServiceContext - - :param sid: The sid - - :returns: twilio.rest.notify.v1.service.ServiceContext - :rtype: twilio.rest.notify.v1.service.ServiceContext + Access the bindings """ - return ServiceContext(self._version, sid=sid, ) + return self._proxy.bindings - def __call__(self, sid): + @property + def notifications(self) -> NotificationList: """ - Constructs a ServiceContext - - :param sid: The sid - - :returns: twilio.rest.notify.v1.service.ServiceContext - :rtype: twilio.rest.notify.v1.service.ServiceContext + Access the notifications """ - return ServiceContext(self._version, sid=sid, ) + return self._proxy.notifications - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ServicePage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class ServiceContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the ServicePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the ServiceContext - :returns: twilio.rest.notify.v1.service.ServicePage - :rtype: twilio.rest.notify.v1.service.ServicePage + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. """ - super(ServicePage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) - def get_instance(self, payload): + self._bindings: Optional[BindingList] = None + self._notifications: Optional[NotificationList] = None + + def delete(self) -> bool: """ - Build an instance of ServiceInstance + Deletes the ServiceInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.notify.v1.service.ServiceInstance - :rtype: twilio.rest.notify.v1.service.ServiceInstance + :returns: True if delete succeeds, False otherwise """ - return ServiceInstance(self._version, payload, ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the ServiceInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class ServiceContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, sid): + def fetch(self) -> ServiceInstance: """ - Initialize the ServiceContext + Fetch the ServiceInstance - :param Version version: Version that contains the resource - :param sid: The sid - :returns: twilio.rest.notify.v1.service.ServiceContext - :rtype: twilio.rest.notify.v1.service.ServiceContext + :returns: The fetched ServiceInstance """ - super(ServiceContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Services/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._bindings = None - self._notifications = None - self._users = None - self._segments = None + headers["Accept"] = "application/json" - def delete(self): - """ - Deletes the ServiceInstance + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def fetch(self): + async def fetch_async(self) -> ServiceInstance: """ - Fetch a ServiceInstance + Asynchronous coroutine to fetch the ServiceInstance - :returns: Fetched ServiceInstance - :rtype: twilio.rest.notify.v1.service.ServiceInstance + + :returns: The fetched ServiceInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], ) + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def update(self, friendly_name=values.unset, apn_credential_sid=values.unset, - gcm_credential_sid=values.unset, messaging_service_sid=values.unset, - facebook_messenger_page_id=values.unset, - default_apn_notification_protocol_version=values.unset, - default_gcm_notification_protocol_version=values.unset, - fcm_credential_sid=values.unset, - default_fcm_notification_protocol_version=values.unset, - log_enabled=values.unset, alexa_skill_id=values.unset, - default_alexa_notification_protocol_version=values.unset): + 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 unicode friendly_name: The friendly_name - :param unicode apn_credential_sid: The apn_credential_sid - :param unicode gcm_credential_sid: The gcm_credential_sid - :param unicode messaging_service_sid: The messaging_service_sid - :param unicode facebook_messenger_page_id: The facebook_messenger_page_id - :param unicode default_apn_notification_protocol_version: The default_apn_notification_protocol_version - :param unicode default_gcm_notification_protocol_version: The default_gcm_notification_protocol_version - :param unicode fcm_credential_sid: The fcm_credential_sid - :param unicode default_fcm_notification_protocol_version: The default_fcm_notification_protocol_version - :param bool log_enabled: The log_enabled - :param unicode alexa_skill_id: The alexa_skill_id - :param unicode default_alexa_notification_protocol_version: The default_alexa_notification_protocol_version - - :returns: Updated ServiceInstance - :rtype: twilio.rest.notify.v1.service.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': log_enabled, - 'AlexaSkillId': alexa_skill_id, - 'DefaultAlexaNotificationProtocolVersion': default_alexa_notification_protocol_version, - }) + :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( - 'POST', - self._uri, - data=data, + 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'], ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) @property - def bindings(self): + def bindings(self) -> BindingList: """ Access the bindings - - :returns: twilio.rest.notify.v1.service.binding.BindingList - :rtype: twilio.rest.notify.v1.service.binding.BindingList """ if self._bindings is None: - self._bindings = BindingList(self._version, service_sid=self._solution['sid'], ) + self._bindings = BindingList( + self._version, + self._solution["sid"], + ) return self._bindings @property - def notifications(self): + def notifications(self) -> NotificationList: """ Access the notifications - - :returns: twilio.rest.notify.v1.service.notification.NotificationList - :rtype: twilio.rest.notify.v1.service.notification.NotificationList """ if self._notifications is None: - self._notifications = NotificationList(self._version, service_sid=self._solution['sid'], ) + self._notifications = NotificationList( + self._version, + self._solution["sid"], + ) return self._notifications - @property - def users(self): + def __repr__(self) -> str: """ - Access the users + Provide a friendly representation - :returns: twilio.rest.notify.v1.service.user.UserList - :rtype: twilio.rest.notify.v1.service.user.UserList + :returns: Machine friendly representation """ - if self._users is None: - self._users = UserList(self._version, service_sid=self._solution['sid'], ) - return self._users + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def segments(self): + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: """ - Access the segments + Build an instance of ServiceInstance - :returns: twilio.rest.notify.v1.service.segment.SegmentList - :rtype: twilio.rest.notify.v1.service.segment.SegmentList + :param payload: Payload response from the API """ - if self._segments is None: - self._segments = SegmentList(self._version, service_sid=self._solution['sid'], ) - return self._segments + return ServiceInstance(self._version, payload) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - + return "" -class ServiceInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, payload, sid=None): - """ - Initialize the ServiceInstance - - :returns: twilio.rest.notify.v1.service.ServiceInstance - :rtype: twilio.rest.notify.v1.service.ServiceInstance - """ - super(ServiceInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'friendly_name': payload['friendly_name'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'apn_credential_sid': payload['apn_credential_sid'], - 'gcm_credential_sid': payload['gcm_credential_sid'], - 'fcm_credential_sid': payload['fcm_credential_sid'], - 'messaging_service_sid': payload['messaging_service_sid'], - 'facebook_messenger_page_id': payload['facebook_messenger_page_id'], - 'default_apn_notification_protocol_version': payload['default_apn_notification_protocol_version'], - 'default_gcm_notification_protocol_version': payload['default_gcm_notification_protocol_version'], - 'default_fcm_notification_protocol_version': payload['default_fcm_notification_protocol_version'], - 'log_enabled': payload['log_enabled'], - 'url': payload['url'], - 'links': payload['links'], - 'alexa_skill_id': payload['alexa_skill_id'], - 'default_alexa_notification_protocol_version': payload['default_alexa_notification_protocol_version'], - } - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } +class ServiceList(ListResource): - @property - def _proxy(self): + def __init__(self, version: Version): """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Initialize the ServiceList - :returns: ServiceContext for this ServiceInstance - :rtype: twilio.rest.notify.v1.service.ServiceContext - """ - if self._context is None: - self._context = ServiceContext(self._version, sid=self._solution['sid'], ) - return self._context + :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"}) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + headers["Accept"] = "application/json" - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + 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"}) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def apn_credential_sid(self): - """ - :returns: The apn_credential_sid - :rtype: unicode - """ - return self._properties['apn_credential_sid'] + headers["Accept"] = "application/json" - @property - def gcm_credential_sid(self): - """ - :returns: The gcm_credential_sid - :rtype: unicode - """ - return self._properties['gcm_credential_sid'] + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def fcm_credential_sid(self): - """ - :returns: The fcm_credential_sid - :rtype: unicode - """ - return self._properties['fcm_credential_sid'] + return ServiceInstance(self._version, payload) - @property - def messaging_service_sid(self): - """ - :returns: The messaging_service_sid - :rtype: unicode + def stream( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: """ - return self._properties['messaging_service_sid'] + 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. - @property - def facebook_messenger_page_id(self): - """ - :returns: The facebook_messenger_page_id - :rtype: unicode - """ - return self._properties['facebook_messenger_page_id'] + :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) - @property - def default_apn_notification_protocol_version(self): - """ - :returns: The default_apn_notification_protocol_version - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['default_apn_notification_protocol_version'] + limits = self._version.read_limits(limit, page_size) + page = self.page(friendly_name=friendly_name, page_size=limits["page_size"]) - @property - def default_gcm_notification_protocol_version(self): - """ - :returns: The default_gcm_notification_protocol_version - :rtype: unicode - """ - return self._properties['default_gcm_notification_protocol_version'] + return self._version.stream(page, limits["limit"]) - @property - def default_fcm_notification_protocol_version(self): + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: """ - :returns: The default_fcm_notification_protocol_version - :rtype: unicode - """ - return self._properties['default_fcm_notification_protocol_version'] + 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. - @property - def log_enabled(self): - """ - :returns: The log_enabled - :rtype: bool - """ - return self._properties['log_enabled'] + :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) - @property - def url(self): - """ - :returns: The url - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['url'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) - @property - def links(self): - """ - :returns: The links - :rtype: unicode - """ - return self._properties['links'] + return self._version.stream_async(page, limits["limit"]) - @property - def alexa_skill_id(self): - """ - :returns: The alexa_skill_id - :rtype: unicode + def list( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: """ - return self._properties['alexa_skill_id'] + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def default_alexa_notification_protocol_version(self): - """ - :returns: The default_alexa_notification_protocol_version - :rtype: unicode - """ - return self._properties['default_alexa_notification_protocol_version'] + :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, + ) + ) - def delete(self): + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: """ - Deletes the 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. - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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: """ - return self._proxy.delete() + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - def fetch(self): - """ - Fetch a ServiceInstance + :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: Fetched ServiceInstance - :rtype: twilio.rest.notify.v1.service.ServiceInstance + :returns: Page of ServiceInstance """ - return self._proxy.fetch() + 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"}) - def update(self, friendly_name=values.unset, apn_credential_sid=values.unset, - gcm_credential_sid=values.unset, messaging_service_sid=values.unset, - facebook_messenger_page_id=values.unset, - default_apn_notification_protocol_version=values.unset, - default_gcm_notification_protocol_version=values.unset, - fcm_credential_sid=values.unset, - default_fcm_notification_protocol_version=values.unset, - log_enabled=values.unset, alexa_skill_id=values.unset, - default_alexa_notification_protocol_version=values.unset): + 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: """ - Update the ServiceInstance + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - :param unicode friendly_name: The friendly_name - :param unicode apn_credential_sid: The apn_credential_sid - :param unicode gcm_credential_sid: The gcm_credential_sid - :param unicode messaging_service_sid: The messaging_service_sid - :param unicode facebook_messenger_page_id: The facebook_messenger_page_id - :param unicode default_apn_notification_protocol_version: The default_apn_notification_protocol_version - :param unicode default_gcm_notification_protocol_version: The default_gcm_notification_protocol_version - :param unicode fcm_credential_sid: The fcm_credential_sid - :param unicode default_fcm_notification_protocol_version: The default_fcm_notification_protocol_version - :param bool log_enabled: The log_enabled - :param unicode alexa_skill_id: The alexa_skill_id - :param unicode default_alexa_notification_protocol_version: The default_alexa_notification_protocol_version - - :returns: Updated ServiceInstance - :rtype: twilio.rest.notify.v1.service.ServiceInstance + :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 """ - 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, + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } ) - @property - def bindings(self): + headers = values.of({"Content-Type": "application/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: """ - Access the bindings + 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: twilio.rest.notify.v1.service.binding.BindingList - :rtype: twilio.rest.notify.v1.service.binding.BindingList + :returns: Page of ServiceInstance """ - return self._proxy.bindings + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) - @property - def notifications(self): + async def get_page_async(self, target_url: str) -> ServicePage: """ - Access the notifications + 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: twilio.rest.notify.v1.service.notification.NotificationList - :rtype: twilio.rest.notify.v1.service.notification.NotificationList + :returns: Page of ServiceInstance """ - return self._proxy.notifications + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) - @property - def users(self): + def get(self, sid: str) -> ServiceContext: """ - Access the users + Constructs a ServiceContext - :returns: twilio.rest.notify.v1.service.user.UserList - :rtype: twilio.rest.notify.v1.service.user.UserList + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. """ - return self._proxy.users + return ServiceContext(self._version, sid=sid) - @property - def segments(self): + def __call__(self, sid: str) -> ServiceContext: """ - Access the segments + Constructs a ServiceContext - :returns: twilio.rest.notify.v1.service.segment.SegmentList - :rtype: twilio.rest.notify.v1.service.segment.SegmentList + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. """ - return self._proxy.segments + return ServiceContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/notify/v1/service/binding.py b/twilio/rest/notify/v1/service/binding.py index a3769ceb89..33b1a4aac0 100644 --- a/twilio/rest/notify/v1/service/binding.py +++ b/twilio/rest/notify/v1/service/binding.py @@ -1,524 +1,681 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 BindingList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class BindingInstance(InstanceResource): - def __init__(self, version, service_sid): - """ - Initialize the BindingList + class BindingType(object): + APN = "apn" + GCM = "gcm" + SMS = "sms" + FCM = "fcm" + FACEBOOK_MESSENGER = "facebook-messenger" + ALEXA = "alexa" - :param Version version: Version that contains the resource - :param service_sid: The service_sid + """ + :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 - :returns: twilio.rest.notify.v1.service.binding.BindingList - :rtype: twilio.rest.notify.v1.service.binding.BindingList + @property + def _proxy(self) -> "BindingContext": """ - super(BindingList, self).__init__(version) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Bindings'.format(**self._solution) - - def create(self, identity, binding_type, address, tag=values.unset, - notification_protocol_version=values.unset, - credential_sid=values.unset, endpoint=values.unset): - """ - Create a new BindingInstance - - :param unicode identity: The identity - :param BindingInstance.BindingType binding_type: The binding_type - :param unicode address: The address - :param unicode tag: The tag - :param unicode notification_protocol_version: The notification_protocol_version - :param unicode credential_sid: The credential_sid - :param unicode endpoint: The endpoint - - :returns: Newly created BindingInstance - :rtype: twilio.rest.notify.v1.service.binding.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, - }) + :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 - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + def delete(self) -> bool: + """ + Deletes the BindingInstance - return BindingInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, start_date=values.unset, end_date=values.unset, - identity=values.unset, tag=values.unset, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BindingInstance - :param date start_date: The start_date - :param date end_date: The end_date - :param unicode identity: The identity - :param unicode tag: The tag - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.notify.v1.service.binding.BindingInstance] + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() - page = self.page( - start_date=start_date, - end_date=end_date, - identity=identity, - tag=tag, - page_size=limits['page_size'], - ) + def fetch(self) -> "BindingInstance": + """ + Fetch the BindingInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, start_date=values.unset, end_date=values.unset, - identity=values.unset, tag=values.unset, limit=None, page_size=None): + :returns: The fetched 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. + return self._proxy.fetch() + + async def fetch_async(self) -> "BindingInstance": + """ + Asynchronous coroutine to fetch the BindingInstance - :param date start_date: The start_date - :param date end_date: The end_date - :param unicode identity: The identity - :param unicode tag: The tag - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.notify.v1.service.binding.BindingInstance] + :returns: The fetched BindingInstance """ - return list(self.stream( - start_date=start_date, - end_date=end_date, - identity=identity, - tag=tag, - limit=limit, - page_size=page_size, - )) + return await self._proxy.fetch_async() - def page(self, start_date=values.unset, end_date=values.unset, - identity=values.unset, tag=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def __repr__(self) -> str: """ - Retrieve a single page of BindingInstance records from the API. - Request is executed immediately + Provide a friendly representation - :param date start_date: The start_date - :param date end_date: The end_date - :param unicode identity: The identity - :param unicode tag: The tag - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: Page of BindingInstance - :rtype: twilio.rest.notify.v1.service.binding.BindingPage - """ - params = 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, - }) - response = self._version.page( - 'GET', - self._uri, - params=params, - ) +class BindingContext(InstanceContext): - return BindingPage(self._version, response, self._solution) + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the BindingContext - def get_page(self, target_url): + :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. """ - Retrieve a specific page of BindingInstance records from the API. - Request is executed immediately + super().__init__(version) - :param str target_url: API-generated URL for the requested results page + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Bindings/{sid}".format(**self._solution) - :returns: Page of BindingInstance - :rtype: twilio.rest.notify.v1.service.binding.BindingPage + def delete(self) -> bool: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Deletes the BindingInstance - return BindingPage(self._version, response, self._solution) - def get(self, sid): + :returns: True if delete succeeds, False otherwise """ - Constructs a BindingContext - :param sid: The sid + headers = values.of({}) - :returns: twilio.rest.notify.v1.service.binding.BindingContext - :rtype: twilio.rest.notify.v1.service.binding.BindingContext - """ - return BindingContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __call__(self, sid): + async def delete_async(self) -> bool: """ - Constructs a BindingContext + Asynchronous coroutine that deletes the BindingInstance - :param sid: The sid - :returns: twilio.rest.notify.v1.service.binding.BindingContext - :rtype: twilio.rest.notify.v1.service.binding.BindingContext + :returns: True if delete succeeds, False otherwise """ - return BindingContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) - def __repr__(self): + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> BindingInstance: """ - Provide a friendly representation + Fetch the BindingInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched BindingInstance """ - return '' + headers = values.of({}) -class BindingPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + 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"], + ) - def __init__(self, version, response, solution): + async def fetch_async(self) -> BindingInstance: """ - Initialize the BindingPage + Asynchronous coroutine to fetch the BindingInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :returns: twilio.rest.notify.v1.service.binding.BindingPage - :rtype: twilio.rest.notify.v1.service.binding.BindingPage + :returns: The fetched BindingInstance """ - super(BindingPage, self).__init__(version, response) - # Path Solution - self._solution = solution + 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 get_instance(self, payload): + def __repr__(self) -> str: """ - Build an instance of BindingInstance + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BindingPage(Page): - :param dict payload: Payload response from the API + def get_instance(self, payload: Dict[str, Any]) -> BindingInstance: + """ + Build an instance of BindingInstance - :returns: twilio.rest.notify.v1.service.binding.BindingInstance - :rtype: twilio.rest.notify.v1.service.binding.BindingInstance + :param payload: Payload response from the API """ - return BindingInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + return BindingInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class BindingContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class BindingList(ListResource): - def __init__(self, version, service_sid, sid): + def __init__(self, version: Version, service_sid: str): """ - Initialize the BindingContext + Initialize the BindingList - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: The sid + :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. - :returns: twilio.rest.notify.v1.service.binding.BindingContext - :rtype: twilio.rest.notify.v1.service.binding.BindingContext """ - super(BindingContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Bindings/{sid}'.format(**self._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"}) - def fetch(self): - """ - Fetch a BindingInstance + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: Fetched BindingInstance - :rtype: twilio.rest.notify.v1.service.binding.BindingInstance - """ - params = values.of({}) + headers["Accept"] = "application/json" - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers ) return BindingInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + self._version, payload, service_sid=self._solution["service_sid"] ) - def delete(self): - """ - Deletes the BindingInstance + 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"}) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __repr__(self): - """ - Provide a friendly representation + headers["Accept"] = "application/json" - :returns: Machine friendly representation - :rtype: str + 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]: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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) -class BindingInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :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"], + ) - class BindingType(object): - APN = "apn" - GCM = "gcm" - SMS = "sms" - FCM = "fcm" - FACEBOOK_MESSENGER = "facebook-messenger" - ALEXA = "alexa" + return self._version.stream(page, limits["limit"]) - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the BindingInstance - - :returns: twilio.rest.notify.v1.service.binding.BindingInstance - :rtype: twilio.rest.notify.v1.service.binding.BindingInstance - """ - super(BindingInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'credential_sid': payload['credential_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'notification_protocol_version': payload['notification_protocol_version'], - 'endpoint': payload['endpoint'], - 'identity': payload['identity'], - 'binding_type': payload['binding_type'], - 'address': payload['address'], - 'tags': payload['tags'], - 'url': payload['url'], - 'links': payload['links'], - } + 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. - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + :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) - @property - def _proxy(self): + :returns: Generator that will yield up to limit results """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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"], + ) - :returns: BindingContext for this BindingInstance - :rtype: twilio.rest.notify.v1.service.binding.BindingContext + 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]: """ - if self._context is None: - self._context = BindingContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + 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, ) - return self._context + ) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + 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. - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + :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: """ - return self._properties['account_sid'] + Retrieve a single page of BindingInstance records from the API. + Request is executed immediately - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] + :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 - @property - def credential_sid(self): - """ - :returns: The credential_sid - :rtype: unicode + :returns: Page of BindingInstance """ - return self._properties['credential_sid'] + 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, + } + ) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Accept"] = "application/json" - @property - def notification_protocol_version(self): - """ - :returns: The notification_protocol_version - :rtype: unicode - """ - return self._properties['notification_protocol_version'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BindingPage(self._version, response, self._solution) - @property - def endpoint(self): - """ - :returns: The endpoint - :rtype: unicode - """ - return self._properties['endpoint'] + 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 - @property - def identity(self): - """ - :returns: The identity - :rtype: unicode - """ - return self._properties['identity'] + :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 - @property - def binding_type(self): - """ - :returns: The binding_type - :rtype: unicode + :returns: Page of BindingInstance """ - return self._properties['binding_type'] + 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, + } + ) - @property - def address(self): - """ - :returns: The address - :rtype: unicode - """ - return self._properties['address'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def tags(self): - """ - :returns: The tags - :rtype: unicode - """ - return self._properties['tags'] + headers["Accept"] = "application/json" - @property - def url(self): + 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: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + response = self._version.domain.twilio.request("GET", target_url) + return BindingPage(self._version, response, self._solution) - @property - def links(self): + async def get_page_async(self, target_url: str) -> BindingPage: """ - :returns: The links - :rtype: unicode + 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 """ - return self._properties['links'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return BindingPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> BindingContext: """ - Fetch a BindingInstance + Constructs a BindingContext - :returns: Fetched BindingInstance - :rtype: twilio.rest.notify.v1.service.binding.BindingInstance + :param sid: The Twilio-provided string that uniquely identifies the Binding resource to fetch. """ - return self._proxy.fetch() + return BindingContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def delete(self): + def __call__(self, sid: str) -> BindingContext: """ - Deletes the BindingInstance + Constructs a BindingContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the Binding resource to fetch. """ - return self._proxy.delete() + return BindingContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/notify/v1/service/notification.py b/twilio/rest/notify/v1/service/notification.py index aebfd21d4f..4d228e864f 100644 --- a/twilio/rest/notify/v1/service/notification.py +++ b/twilio/rest/notify/v1/service/notification.py @@ -1,358 +1,285 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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.page import Page - - -class NotificationList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, service_sid): - """ - Initialize the NotificationList - - :param Version version: Version that contains the resource - :param service_sid: The service_sid - - :returns: twilio.rest.notify.v1.service.notification.NotificationList - :rtype: twilio.rest.notify.v1.service.notification.NotificationList - """ - super(NotificationList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Notifications'.format(**self._solution) - - def create(self, body=values.unset, priority=values.unset, ttl=values.unset, - title=values.unset, sound=values.unset, action=values.unset, - data=values.unset, apn=values.unset, gcm=values.unset, - sms=values.unset, facebook_messenger=values.unset, fcm=values.unset, - segment=values.unset, alexa=values.unset, to_binding=values.unset, - identity=values.unset, tag=values.unset): - """ - Create a new NotificationInstance - - :param unicode body: The body - :param NotificationInstance.Priority priority: The priority - :param unicode ttl: The ttl - :param unicode title: The title - :param unicode sound: The sound - :param unicode action: The action - :param dict data: The data - :param dict apn: The apn - :param dict gcm: The gcm - :param dict sms: The sms - :param dict facebook_messenger: The facebook_messenger - :param dict fcm: The fcm - :param unicode segment: The segment - :param dict alexa: The alexa - :param unicode to_binding: The to_binding - :param unicode identity: The identity - :param unicode tag: The tag - - :returns: Newly created NotificationInstance - :rtype: twilio.rest.notify.v1.service.notification.NotificationInstance - """ - data = values.of({ - 'Identity': serialize.map(identity, lambda e: e), - 'Tag': serialize.map(tag, lambda e: e), - '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), - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return NotificationInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class NotificationPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, response, solution): - """ - Initialize the NotificationPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - - :returns: twilio.rest.notify.v1.service.notification.NotificationPage - :rtype: twilio.rest.notify.v1.service.notification.NotificationPage - """ - super(NotificationPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of NotificationInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.notify.v1.service.notification.NotificationInstance - :rtype: twilio.rest.notify.v1.service.notification.NotificationInstance - """ - return NotificationInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' +from twilio.base.version import Version class NotificationInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ class Priority(object): HIGH = "high" LOW = "low" - def __init__(self, version, payload, service_sid): - """ - Initialize the NotificationInstance + """ + :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") - :returns: twilio.rest.notify.v1.service.notification.NotificationInstance - :rtype: twilio.rest.notify.v1.service.notification.NotificationInstance - """ - super(NotificationInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'identities': payload['identities'], - 'tags': payload['tags'], - 'segments': payload['segments'], - 'priority': payload['priority'], - 'ttl': deserialize.integer(payload['ttl']), - 'title': payload['title'], - 'body': payload['body'], - 'sound': payload['sound'], - 'action': payload['action'], - 'data': payload['data'], - 'apn': payload['apn'], - 'gcm': payload['gcm'], - 'fcm': payload['fcm'], - 'sms': payload['sms'], - 'facebook_messenger': payload['facebook_messenger'], - 'alexa': payload['alexa'], + self._solution = { + "service_sid": service_sid, } - # Context - self._context = None - self._solution = {'service_sid': service_sid, } - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['sid'] - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + Provide a friendly representation - @property - def identities(self): - """ - :returns: The identities - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['identities'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def tags(self): - """ - :returns: The tags - :rtype: unicode - """ - return self._properties['tags'] - @property - def segments(self): - """ - :returns: The segments - :rtype: unicode - """ - return self._properties['segments'] +class NotificationList(ListResource): - @property - def priority(self): + def __init__(self, version: Version, service_sid: str): """ - :returns: The priority - :rtype: NotificationInstance.Priority - """ - return self._properties['priority'] + Initialize the NotificationList - @property - def ttl(self): - """ - :returns: The ttl - :rtype: unicode - """ - return self._properties['ttl'] + :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. - @property - def title(self): - """ - :returns: The title - :rtype: unicode """ - return self._properties['title'] + super().__init__(version) - @property - def body(self): - """ - :returns: The body - :rtype: unicode - """ - return self._properties['body'] + # 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"}) - @property - def sound(self): - """ - :returns: The sound - :rtype: unicode - """ - return self._properties['sound'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def action(self): - """ - :returns: The action - :rtype: unicode - """ - return self._properties['action'] + headers["Accept"] = "application/json" - @property - def data(self): - """ - :returns: The data - :rtype: dict - """ - return self._properties['data'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def apn(self): - """ - :returns: The apn - :rtype: dict - """ - return self._properties['apn'] + return NotificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def gcm(self): - """ - :returns: The gcm - :rtype: dict - """ - return self._properties['gcm'] + 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"}) - @property - def fcm(self): - """ - :returns: The fcm - :rtype: dict - """ - return self._properties['fcm'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def sms(self): - """ - :returns: The sms - :rtype: dict - """ - return self._properties['sms'] + headers["Accept"] = "application/json" - @property - def facebook_messenger(self): - """ - :returns: The facebook_messenger - :rtype: dict - """ - return self._properties['facebook_messenger'] + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def alexa(self): - """ - :returns: The alexa - :rtype: dict - """ - return self._properties['alexa'] + return NotificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/notify/v1/service/segment.py b/twilio/rest/notify/v1/service/segment.py deleted file mode 100644 index 270f5631f9..0000000000 --- a/twilio/rest/notify/v1/service/segment.py +++ /dev/null @@ -1,250 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import values -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.page import Page - - -class SegmentList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, service_sid): - """ - Initialize the SegmentList - - :param Version version: Version that contains the resource - :param service_sid: The service_sid - - :returns: twilio.rest.notify.v1.service.segment.SegmentList - :rtype: twilio.rest.notify.v1.service.segment.SegmentList - """ - super(SegmentList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Segments'.format(**self._solution) - - def stream(self, limit=None, page_size=None): - """ - Streams SegmentInstance records from the API as a generator stream. - This operation lazily loads 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 limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.notify.v1.service.segment.SegmentInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists SegmentInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.notify.v1.service.segment.SegmentInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of SegmentInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of SegmentInstance - :rtype: twilio.rest.notify.v1.service.segment.SegmentPage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return SegmentPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of SegmentInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of SegmentInstance - :rtype: twilio.rest.notify.v1.service.segment.SegmentPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return SegmentPage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SegmentPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, response, solution): - """ - Initialize the SegmentPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - - :returns: twilio.rest.notify.v1.service.segment.SegmentPage - :rtype: twilio.rest.notify.v1.service.segment.SegmentPage - """ - super(SegmentPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of SegmentInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.notify.v1.service.segment.SegmentInstance - :rtype: twilio.rest.notify.v1.service.segment.SegmentInstance - """ - return SegmentInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SegmentInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, payload, service_sid): - """ - Initialize the SegmentInstance - - :returns: twilio.rest.notify.v1.service.segment.SegmentInstance - :rtype: twilio.rest.notify.v1.service.segment.SegmentInstance - """ - super(SegmentInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'unique_name': payload['unique_name'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - } - - # Context - self._context = None - self._solution = {'service_sid': service_sid, } - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] - - @property - def unique_name(self): - """ - :returns: The unique_name - :rtype: unicode - """ - return self._properties['unique_name'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/notify/v1/service/user/__init__.py b/twilio/rest/notify/v1/service/user/__init__.py deleted file mode 100644 index ee79f6625b..0000000000 --- a/twilio/rest/notify/v1/service/user/__init__.py +++ /dev/null @@ -1,493 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import serialize -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.page import Page -from twilio.rest.notify.v1.service.user.segment_memberships import SegmentMembershipList -from twilio.rest.notify.v1.service.user.user_binding import UserBindingList - - -class UserList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, service_sid): - """ - Initialize the UserList - - :param Version version: Version that contains the resource - :param service_sid: The service_sid - - :returns: twilio.rest.notify.v1.service.user.UserList - :rtype: twilio.rest.notify.v1.service.user.UserList - """ - super(UserList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Users'.format(**self._solution) - - def create(self, identity, segment=values.unset): - """ - Create a new UserInstance - - :param unicode identity: The identity - :param unicode segment: The segment - - :returns: Newly created UserInstance - :rtype: twilio.rest.notify.v1.service.user.UserInstance - """ - data = values.of({'Identity': identity, 'Segment': serialize.map(segment, lambda e: e), }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return UserInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def stream(self, identity=values.unset, segment=values.unset, limit=None, - page_size=None): - """ - 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 unicode identity: The identity - :param unicode segment: The segment - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.notify.v1.service.user.UserInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(identity=identity, segment=segment, page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, identity=values.unset, segment=values.unset, limit=None, - page_size=None): - """ - 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 unicode identity: The identity - :param unicode segment: The segment - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.notify.v1.service.user.UserInstance] - """ - return list(self.stream(identity=identity, segment=segment, limit=limit, page_size=page_size, )) - - def page(self, identity=values.unset, segment=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of UserInstance records from the API. - Request is executed immediately - - :param unicode identity: The identity - :param unicode segment: The segment - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of UserInstance - :rtype: twilio.rest.notify.v1.service.user.UserPage - """ - params = values.of({ - 'Identity': serialize.map(identity, lambda e: e), - 'Segment': segment, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return UserPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of UserInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of UserInstance - :rtype: twilio.rest.notify.v1.service.user.UserPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return UserPage(self._version, response, self._solution) - - def get(self, identity): - """ - Constructs a UserContext - - :param identity: The identity - - :returns: twilio.rest.notify.v1.service.user.UserContext - :rtype: twilio.rest.notify.v1.service.user.UserContext - """ - return UserContext(self._version, service_sid=self._solution['service_sid'], identity=identity, ) - - def __call__(self, identity): - """ - Constructs a UserContext - - :param identity: The identity - - :returns: twilio.rest.notify.v1.service.user.UserContext - :rtype: twilio.rest.notify.v1.service.user.UserContext - """ - return UserContext(self._version, service_sid=self._solution['service_sid'], identity=identity, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class UserPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, response, solution): - """ - Initialize the UserPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - - :returns: twilio.rest.notify.v1.service.user.UserPage - :rtype: twilio.rest.notify.v1.service.user.UserPage - """ - super(UserPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of UserInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.notify.v1.service.user.UserInstance - :rtype: twilio.rest.notify.v1.service.user.UserInstance - """ - return UserInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class UserContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, service_sid, identity): - """ - Initialize the UserContext - - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param identity: The identity - - :returns: twilio.rest.notify.v1.service.user.UserContext - :rtype: twilio.rest.notify.v1.service.user.UserContext - """ - super(UserContext, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, 'identity': identity, } - self._uri = '/Services/{service_sid}/Users/{identity}'.format(**self._solution) - - # Dependents - self._bindings = None - self._segment_memberships = None - - def delete(self): - """ - Deletes the UserInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def fetch(self): - """ - Fetch a UserInstance - - :returns: Fetched UserInstance - :rtype: twilio.rest.notify.v1.service.user.UserInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return UserInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - ) - - @property - def bindings(self): - """ - Access the bindings - - :returns: twilio.rest.notify.v1.service.user.user_binding.UserBindingList - :rtype: twilio.rest.notify.v1.service.user.user_binding.UserBindingList - """ - if self._bindings is None: - self._bindings = UserBindingList( - self._version, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - ) - return self._bindings - - @property - def segment_memberships(self): - """ - Access the segment_memberships - - :returns: twilio.rest.notify.v1.service.user.segment_memberships.SegmentMembershipList - :rtype: twilio.rest.notify.v1.service.user.segment_memberships.SegmentMembershipList - """ - if self._segment_memberships is None: - self._segment_memberships = SegmentMembershipList( - self._version, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - ) - return self._segment_memberships - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class UserInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, payload, service_sid, identity=None): - """ - Initialize the UserInstance - - :returns: twilio.rest.notify.v1.service.user.UserInstance - :rtype: twilio.rest.notify.v1.service.user.UserInstance - """ - super(UserInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'identity': payload['identity'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'segments': payload['segments'], - 'url': payload['url'], - 'links': payload['links'], - } - - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'identity': identity or self._properties['identity'], } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.notify.v1.service.user.UserContext - """ - if self._context is None: - self._context = UserContext( - self._version, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - ) - return self._context - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] - - @property - def identity(self): - """ - :returns: The identity - :rtype: unicode - """ - return self._properties['identity'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def segments(self): - """ - :returns: The segments - :rtype: unicode - """ - return self._properties['segments'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def links(self): - """ - :returns: The links - :rtype: unicode - """ - return self._properties['links'] - - def delete(self): - """ - Deletes the UserInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def fetch(self): - """ - Fetch a UserInstance - - :returns: Fetched UserInstance - :rtype: twilio.rest.notify.v1.service.user.UserInstance - """ - return self._proxy.fetch() - - @property - def bindings(self): - """ - Access the bindings - - :returns: twilio.rest.notify.v1.service.user.user_binding.UserBindingList - :rtype: twilio.rest.notify.v1.service.user.user_binding.UserBindingList - """ - return self._proxy.bindings - - @property - def segment_memberships(self): - """ - Access the segment_memberships - - :returns: twilio.rest.notify.v1.service.user.segment_memberships.SegmentMembershipList - :rtype: twilio.rest.notify.v1.service.user.segment_memberships.SegmentMembershipList - """ - return self._proxy.segment_memberships - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/notify/v1/service/user/segment_memberships.py b/twilio/rest/notify/v1/service/user/segment_memberships.py deleted file mode 100644 index c34dbf3fc6..0000000000 --- a/twilio/rest/notify/v1/service/user/segment_memberships.py +++ /dev/null @@ -1,329 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -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.page import Page - - -class SegmentMembershipList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, service_sid, identity): - """ - Initialize the SegmentMembershipList - - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param identity: The identity - - :returns: twilio.rest.notify.v1.service.user.segment_memberships.SegmentMembershipList - :rtype: twilio.rest.notify.v1.service.user.segment_memberships.SegmentMembershipList - """ - super(SegmentMembershipList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, 'identity': identity, } - self._uri = '/Services/{service_sid}/Users/{identity}/SegmentMemberships'.format(**self._solution) - - def create(self, segment): - """ - Create a new SegmentMembershipInstance - - :param unicode segment: The segment - - :returns: Newly created SegmentMembershipInstance - :rtype: twilio.rest.notify.v1.service.user.segment_memberships.SegmentMembershipInstance - """ - data = values.of({'Segment': segment, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return SegmentMembershipInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - ) - - def get(self, segment): - """ - Constructs a SegmentMembershipContext - - :param segment: The segment - - :returns: twilio.rest.notify.v1.service.user.segment_memberships.SegmentMembershipContext - :rtype: twilio.rest.notify.v1.service.user.segment_memberships.SegmentMembershipContext - """ - return SegmentMembershipContext( - self._version, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - segment=segment, - ) - - def __call__(self, segment): - """ - Constructs a SegmentMembershipContext - - :param segment: The segment - - :returns: twilio.rest.notify.v1.service.user.segment_memberships.SegmentMembershipContext - :rtype: twilio.rest.notify.v1.service.user.segment_memberships.SegmentMembershipContext - """ - return SegmentMembershipContext( - self._version, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - segment=segment, - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SegmentMembershipPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, response, solution): - """ - Initialize the SegmentMembershipPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :param identity: The identity - - :returns: twilio.rest.notify.v1.service.user.segment_memberships.SegmentMembershipPage - :rtype: twilio.rest.notify.v1.service.user.segment_memberships.SegmentMembershipPage - """ - super(SegmentMembershipPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of SegmentMembershipInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.notify.v1.service.user.segment_memberships.SegmentMembershipInstance - :rtype: twilio.rest.notify.v1.service.user.segment_memberships.SegmentMembershipInstance - """ - return SegmentMembershipInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SegmentMembershipContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, service_sid, identity, segment): - """ - Initialize the SegmentMembershipContext - - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param identity: The identity - :param segment: The segment - - :returns: twilio.rest.notify.v1.service.user.segment_memberships.SegmentMembershipContext - :rtype: twilio.rest.notify.v1.service.user.segment_memberships.SegmentMembershipContext - """ - super(SegmentMembershipContext, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, 'identity': identity, 'segment': segment, } - self._uri = '/Services/{service_sid}/Users/{identity}/SegmentMemberships/{segment}'.format(**self._solution) - - def delete(self): - """ - Deletes the SegmentMembershipInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def fetch(self): - """ - Fetch a SegmentMembershipInstance - - :returns: Fetched SegmentMembershipInstance - :rtype: twilio.rest.notify.v1.service.user.segment_memberships.SegmentMembershipInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return SegmentMembershipInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - segment=self._solution['segment'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class SegmentMembershipInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, payload, service_sid, identity, segment=None): - """ - Initialize the SegmentMembershipInstance - - :returns: twilio.rest.notify.v1.service.user.segment_memberships.SegmentMembershipInstance - :rtype: twilio.rest.notify.v1.service.user.segment_memberships.SegmentMembershipInstance - """ - super(SegmentMembershipInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'identity': payload['identity'], - 'segment': payload['segment'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'identity': identity, - 'segment': segment or self._properties['segment'], - } - - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: SegmentMembershipContext for this SegmentMembershipInstance - :rtype: twilio.rest.notify.v1.service.user.segment_memberships.SegmentMembershipContext - """ - if self._context is None: - self._context = SegmentMembershipContext( - self._version, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - segment=self._solution['segment'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] - - @property - def identity(self): - """ - :returns: The identity - :rtype: unicode - """ - return self._properties['identity'] - - @property - def segment(self): - """ - :returns: The segment - :rtype: unicode - """ - return self._properties['segment'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - def delete(self): - """ - Deletes the SegmentMembershipInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def fetch(self): - """ - Fetch a SegmentMembershipInstance - - :returns: Fetched SegmentMembershipInstance - :rtype: twilio.rest.notify.v1.service.user.segment_memberships.SegmentMembershipInstance - """ - return self._proxy.fetch() - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/notify/v1/service/user/user_binding.py b/twilio/rest/notify/v1/service/user/user_binding.py deleted file mode 100644 index 8112af68ae..0000000000 --- a/twilio/rest/notify/v1/service/user/user_binding.py +++ /dev/null @@ -1,540 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import serialize -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.page import Page - - -class UserBindingList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, service_sid, identity): - """ - Initialize the UserBindingList - - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param identity: The identity - - :returns: twilio.rest.notify.v1.service.user.user_binding.UserBindingList - :rtype: twilio.rest.notify.v1.service.user.user_binding.UserBindingList - """ - super(UserBindingList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, 'identity': identity, } - self._uri = '/Services/{service_sid}/Users/{identity}/Bindings'.format(**self._solution) - - def create(self, binding_type, address, tag=values.unset, - notification_protocol_version=values.unset, - credential_sid=values.unset, endpoint=values.unset): - """ - Create a new UserBindingInstance - - :param UserBindingInstance.BindingType binding_type: The binding_type - :param unicode address: The address - :param unicode tag: The tag - :param unicode notification_protocol_version: The notification_protocol_version - :param unicode credential_sid: The credential_sid - :param unicode endpoint: The endpoint - - :returns: Newly created UserBindingInstance - :rtype: twilio.rest.notify.v1.service.user.user_binding.UserBindingInstance - """ - data = values.of({ - 'BindingType': binding_type, - 'Address': address, - 'Tag': serialize.map(tag, lambda e: e), - 'NotificationProtocolVersion': notification_protocol_version, - 'CredentialSid': credential_sid, - 'Endpoint': endpoint, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return UserBindingInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - ) - - def stream(self, start_date=values.unset, end_date=values.unset, - tag=values.unset, limit=None, page_size=None): - """ - 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 date start_date: The start_date - :param date end_date: The end_date - :param unicode tag: The tag - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.notify.v1.service.user.user_binding.UserBindingInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(start_date=start_date, end_date=end_date, tag=tag, page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, start_date=values.unset, end_date=values.unset, tag=values.unset, - limit=None, page_size=None): - """ - 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 date start_date: The start_date - :param date end_date: The end_date - :param unicode tag: The tag - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.notify.v1.service.user.user_binding.UserBindingInstance] - """ - return list(self.stream( - start_date=start_date, - end_date=end_date, - tag=tag, - limit=limit, - page_size=page_size, - )) - - def page(self, start_date=values.unset, end_date=values.unset, tag=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of UserBindingInstance records from the API. - Request is executed immediately - - :param date start_date: The start_date - :param date end_date: The end_date - :param unicode tag: The tag - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of UserBindingInstance - :rtype: twilio.rest.notify.v1.service.user.user_binding.UserBindingPage - """ - params = values.of({ - 'StartDate': serialize.iso8601_date(start_date), - 'EndDate': serialize.iso8601_date(end_date), - 'Tag': serialize.map(tag, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return UserBindingPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of UserBindingInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of UserBindingInstance - :rtype: twilio.rest.notify.v1.service.user.user_binding.UserBindingPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return UserBindingPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a UserBindingContext - - :param sid: The sid - - :returns: twilio.rest.notify.v1.service.user.user_binding.UserBindingContext - :rtype: twilio.rest.notify.v1.service.user.user_binding.UserBindingContext - """ - return UserBindingContext( - self._version, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - sid=sid, - ) - - def __call__(self, sid): - """ - Constructs a UserBindingContext - - :param sid: The sid - - :returns: twilio.rest.notify.v1.service.user.user_binding.UserBindingContext - :rtype: twilio.rest.notify.v1.service.user.user_binding.UserBindingContext - """ - return UserBindingContext( - self._version, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - sid=sid, - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class UserBindingPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, response, solution): - """ - Initialize the UserBindingPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :param identity: The identity - - :returns: twilio.rest.notify.v1.service.user.user_binding.UserBindingPage - :rtype: twilio.rest.notify.v1.service.user.user_binding.UserBindingPage - """ - super(UserBindingPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of UserBindingInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.notify.v1.service.user.user_binding.UserBindingInstance - :rtype: twilio.rest.notify.v1.service.user.user_binding.UserBindingInstance - """ - return UserBindingInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class UserBindingContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, service_sid, identity, sid): - """ - Initialize the UserBindingContext - - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param identity: The identity - :param sid: The sid - - :returns: twilio.rest.notify.v1.service.user.user_binding.UserBindingContext - :rtype: twilio.rest.notify.v1.service.user.user_binding.UserBindingContext - """ - super(UserBindingContext, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, 'identity': identity, 'sid': sid, } - self._uri = '/Services/{service_sid}/Users/{identity}/Bindings/{sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch a UserBindingInstance - - :returns: Fetched UserBindingInstance - :rtype: twilio.rest.notify.v1.service.user.user_binding.UserBindingInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return UserBindingInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the UserBindingInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class UserBindingInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - class BindingType(object): - APN = "apn" - GCM = "gcm" - SMS = "sms" - FCM = "fcm" - FACEBOOK_MESSENGER = "facebook-messenger" - ALEXA = "alexa" - - def __init__(self, version, payload, service_sid, identity, sid=None): - """ - Initialize the UserBindingInstance - - :returns: twilio.rest.notify.v1.service.user.user_binding.UserBindingInstance - :rtype: twilio.rest.notify.v1.service.user.user_binding.UserBindingInstance - """ - super(UserBindingInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'credential_sid': payload['credential_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'notification_protocol_version': payload['notification_protocol_version'], - 'endpoint': payload['endpoint'], - 'identity': payload['identity'], - 'binding_type': payload['binding_type'], - 'address': payload['address'], - 'tags': payload['tags'], - 'url': payload['url'], - 'links': payload['links'], - } - - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'identity': identity, - 'sid': sid or self._properties['sid'], - } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.notify.v1.service.user.user_binding.UserBindingContext - """ - if self._context is None: - self._context = UserBindingContext( - self._version, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - sid=self._solution['sid'], - ) - return self._context - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] - - @property - def credential_sid(self): - """ - :returns: The credential_sid - :rtype: unicode - """ - return self._properties['credential_sid'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def notification_protocol_version(self): - """ - :returns: The notification_protocol_version - :rtype: unicode - """ - return self._properties['notification_protocol_version'] - - @property - def endpoint(self): - """ - :returns: The endpoint - :rtype: unicode - """ - return self._properties['endpoint'] - - @property - def identity(self): - """ - :returns: The identity - :rtype: unicode - """ - return self._properties['identity'] - - @property - def binding_type(self): - """ - :returns: The binding_type - :rtype: unicode - """ - return self._properties['binding_type'] - - @property - def address(self): - """ - :returns: The address - :rtype: unicode - """ - return self._properties['address'] - - @property - def tags(self): - """ - :returns: The tags - :rtype: unicode - """ - return self._properties['tags'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def links(self): - """ - :returns: The links - :rtype: unicode - """ - return self._properties['links'] - - def fetch(self): - """ - Fetch a UserBindingInstance - - :returns: Fetched UserBindingInstance - :rtype: twilio.rest.notify.v1.service.user.user_binding.UserBindingInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the UserBindingInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) 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 "" 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 "" 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 "".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 "".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 "" 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 "" + + +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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" 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 "" + + +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 "" 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 "".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 "" 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 "" + + +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 "" 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 "" + + +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 "" + + +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 "" 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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "" + + +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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "" 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 "" 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 "" + + +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 "" 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 "" + + +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 "" 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 "" diff --git a/twilio/rest/preview/__init__.py b/twilio/rest/preview/__init__.py index ffa3bcd72d..501ae417d0 100644 --- a/twilio/rest/preview/__init__.py +++ b/twilio/rest/preview/__init__.py @@ -1,245 +1,88 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base.domain import Domain -from twilio.rest.preview.acc_security import AccSecurity -from twilio.rest.preview.bulk_exports import BulkExports -from twilio.rest.preview.deployed_devices import DeployedDevices -from twilio.rest.preview.hosted_numbers import HostedNumbers -from twilio.rest.preview.marketplace import Marketplace -from twilio.rest.preview.proxy import Proxy -from twilio.rest.preview.studio import Studio -from twilio.rest.preview.sync import Sync -from twilio.rest.preview.understand import Understand -from twilio.rest.preview.wireless import Wireless - - -class Preview(Domain): - - def __init__(self, twilio): - """ - Initialize the Preview Domain - - :returns: Domain for Preview - :rtype: twilio.rest.preview.Preview - """ - super(Preview, self).__init__(twilio) - - self.base_url = 'https://preview.twilio.com' - - # Versions - self._bulk_exports = None - self._deployed_devices = None - self._hosted_numbers = None - self._marketplace = None - self._proxy = None - self._studio = None - self._acc_security = None - self._sync = None - self._understand = None - self._wireless = None - - @property - def bulk_exports(self): - """ - :returns: Version bulk_exports of preview - :rtype: twilio.rest.preview.bulk_exports.BulkExports - """ - if self._bulk_exports is None: - self._bulk_exports = BulkExports(self) - return self._bulk_exports - - @property - def deployed_devices(self): - """ - :returns: Version deployed_devices of preview - :rtype: twilio.rest.preview.deployed_devices.DeployedDevices - """ - if self._deployed_devices is None: - self._deployed_devices = DeployedDevices(self) - return self._deployed_devices - - @property - def hosted_numbers(self): - """ - :returns: Version hosted_numbers of preview - :rtype: twilio.rest.preview.hosted_numbers.HostedNumbers - """ - if self._hosted_numbers is None: - self._hosted_numbers = HostedNumbers(self) - return self._hosted_numbers - - @property - def marketplace(self): - """ - :returns: Version marketplace of preview - :rtype: twilio.rest.preview.marketplace.Marketplace - """ - if self._marketplace is None: - self._marketplace = Marketplace(self) - return self._marketplace - - @property - def proxy(self): - """ - :returns: Version proxy of preview - :rtype: twilio.rest.preview.proxy.Proxy - """ - if self._proxy is None: - self._proxy = Proxy(self) - return self._proxy - - @property - def studio(self): - """ - :returns: Version studio of preview - :rtype: twilio.rest.preview.studio.Studio - """ - if self._studio is None: - self._studio = Studio(self) - return self._studio - - @property - def acc_security(self): - """ - :returns: Version acc_security of preview - :rtype: twilio.rest.preview.acc_security.AccSecurity - """ - if self._acc_security is None: - self._acc_security = AccSecurity(self) - return self._acc_security - - @property - def sync(self): - """ - :returns: Version sync of preview - :rtype: twilio.rest.preview.sync.Sync - """ - if self._sync is None: - self._sync = Sync(self) - return self._sync - - @property - def understand(self): - """ - :returns: Version understand of preview - :rtype: twilio.rest.preview.understand.Understand - """ - if self._understand is None: - self._understand = Understand(self) - return self._understand - - @property - def wireless(self): - """ - :returns: Version wireless of preview - :rtype: twilio.rest.preview.wireless.Wireless - """ - if self._wireless is None: - self._wireless = Wireless(self) - return self._wireless - - @property - def exports(self): - """ - :rtype: twilio.rest.preview.bulk_exports.export.ExportList - """ - return self.bulk_exports.exports - - @property - def export_configuration(self): - """ - :rtype: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationList - """ - return self.bulk_exports.export_configuration - - @property - def fleets(self): - """ - :rtype: twilio.rest.preview.deployed_devices.fleet.FleetList - """ - return self.deployed_devices.fleets - - @property - def authorization_documents(self): - """ - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentList - """ +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): - """ - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderList - """ + 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): - """ - :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnList - """ + 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): - """ - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnList - """ + 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): - """ - :rtype: twilio.rest.preview.sync.service.ServiceList - """ + def services(self) -> ServiceList: + warn( + "services is deprecated. Use sync.services instead.", + DeprecationWarning, + stacklevel=2, + ) return self.sync.services @property - def flows(self): - """ - :rtype: twilio.rest.preview.studio.flow.FlowList - """ - return self.studio.flows - - @property - def assistants(self): - """ - :rtype: twilio.rest.preview.understand.assistant.AssistantList - """ - return self.understand.assistants - - @property - def commands(self): - """ - :rtype: twilio.rest.preview.wireless.command.CommandList - """ + def commands(self) -> CommandList: + warn( + "commands is deprecated. Use wireless.commands instead.", + DeprecationWarning, + stacklevel=2, + ) return self.wireless.commands @property - def rate_plans(self): - """ - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanList - """ + 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): - """ - :rtype: twilio.rest.preview.wireless.sim.SimList - """ + def sims(self) -> SimList: + warn( + "sims is deprecated. Use wireless.sims instead.", + DeprecationWarning, + stacklevel=2, + ) return self.wireless.sims - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/preview/acc_security/__init__.py b/twilio/rest/preview/acc_security/__init__.py deleted file mode 100644 index e63b8d9337..0000000000 --- a/twilio/rest/preview/acc_security/__init__.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base.version import Version -from twilio.rest.preview.acc_security.service import ServiceList - - -class AccSecurity(Version): - - def __init__(self, domain): - """ - Initialize the AccSecurity version of Preview - - :returns: AccSecurity version of Preview - :rtype: twilio.rest.preview.acc_security.AccSecurity.AccSecurity - """ - super(AccSecurity, self).__init__(domain) - self.version = 'Verification' - self._services = None - - @property - def services(self): - """ - :rtype: twilio.rest.preview.acc_security.service.ServiceList - """ - if self._services is None: - self._services = ServiceList(self) - return self._services - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/preview/acc_security/service/__init__.py b/twilio/rest/preview/acc_security/service/__init__.py deleted file mode 100644 index eebdb942a2..0000000000 --- a/twilio/rest/preview/acc_security/service/__init__.py +++ /dev/null @@ -1,466 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page -from twilio.rest.preview.acc_security.service.verification import VerificationList -from twilio.rest.preview.acc_security.service.verification_check import VerificationCheckList - - -class ServiceList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version): - """ - Initialize the ServiceList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.preview.acc_security.service.ServiceList - :rtype: twilio.rest.preview.acc_security.service.ServiceList - """ - super(ServiceList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Services'.format(**self._solution) - - def create(self, name, code_length=values.unset): - """ - Create a new ServiceInstance - - :param unicode name: Friendly name of the service - :param unicode code_length: Length of verification code. Valid values are 4-10 - - :returns: Newly created ServiceInstance - :rtype: twilio.rest.preview.acc_security.service.ServiceInstance - """ - data = values.of({'Name': name, 'CodeLength': code_length, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return ServiceInstance(self._version, payload, ) - - def stream(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.acc_security.service.ServiceInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.acc_security.service.ServiceInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of ServiceInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of ServiceInstance - :rtype: twilio.rest.preview.acc_security.service.ServicePage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return ServicePage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of ServiceInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of ServiceInstance - :rtype: twilio.rest.preview.acc_security.service.ServicePage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ServicePage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a ServiceContext - - :param sid: Verification Service Instance SID. - - :returns: twilio.rest.preview.acc_security.service.ServiceContext - :rtype: twilio.rest.preview.acc_security.service.ServiceContext - """ - return ServiceContext(self._version, sid=sid, ) - - def __call__(self, sid): - """ - Constructs a ServiceContext - - :param sid: Verification Service Instance SID. - - :returns: twilio.rest.preview.acc_security.service.ServiceContext - :rtype: twilio.rest.preview.acc_security.service.ServiceContext - """ - return ServiceContext(self._version, sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ServicePage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the ServicePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.preview.acc_security.service.ServicePage - :rtype: twilio.rest.preview.acc_security.service.ServicePage - """ - super(ServicePage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of ServiceInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.acc_security.service.ServiceInstance - :rtype: twilio.rest.preview.acc_security.service.ServiceInstance - """ - return ServiceInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ServiceContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, sid): - """ - Initialize the ServiceContext - - :param Version version: Version that contains the resource - :param sid: Verification Service Instance SID. - - :returns: twilio.rest.preview.acc_security.service.ServiceContext - :rtype: twilio.rest.preview.acc_security.service.ServiceContext - """ - super(ServiceContext, self).__init__(version) - - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Services/{sid}'.format(**self._solution) - - # Dependents - self._verifications = None - self._verification_checks = None - - def fetch(self): - """ - Fetch a ServiceInstance - - :returns: Fetched ServiceInstance - :rtype: twilio.rest.preview.acc_security.service.ServiceInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) - - def update(self, name=values.unset, code_length=values.unset): - """ - Update the ServiceInstance - - :param unicode name: Friendly name of the service - :param unicode code_length: Length of verification code. Valid values are 4-10 - - :returns: Updated ServiceInstance - :rtype: twilio.rest.preview.acc_security.service.ServiceInstance - """ - data = values.of({'Name': name, 'CodeLength': code_length, }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) - - @property - def verifications(self): - """ - Access the verifications - - :returns: twilio.rest.preview.acc_security.service.verification.VerificationList - :rtype: twilio.rest.preview.acc_security.service.verification.VerificationList - """ - if self._verifications is None: - self._verifications = VerificationList(self._version, service_sid=self._solution['sid'], ) - return self._verifications - - @property - def verification_checks(self): - """ - Access the verification_checks - - :returns: twilio.rest.preview.acc_security.service.verification_check.VerificationCheckList - :rtype: twilio.rest.preview.acc_security.service.verification_check.VerificationCheckList - """ - if self._verification_checks is None: - self._verification_checks = VerificationCheckList(self._version, service_sid=self._solution['sid'], ) - return self._verification_checks - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class ServiceInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, sid=None): - """ - Initialize the ServiceInstance - - :returns: twilio.rest.preview.acc_security.service.ServiceInstance - :rtype: twilio.rest.preview.acc_security.service.ServiceInstance - """ - super(ServiceInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'name': payload['name'], - 'code_length': deserialize.integer(payload['code_length']), - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - 'links': payload['links'], - } - - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.acc_security.service.ServiceContext - """ - if self._context is None: - self._context = ServiceContext(self._version, sid=self._solution['sid'], ) - return self._context - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Service. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def name(self): - """ - :returns: Friendly name of the service - :rtype: unicode - """ - return self._properties['name'] - - @property - def code_length(self): - """ - :returns: Length of verification code. Valid values are 4-10 - :rtype: unicode - """ - return self._properties['code_length'] - - @property - def date_created(self): - """ - :returns: The date this Service was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date this Service was updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def links(self): - """ - :returns: The links - :rtype: unicode - """ - return self._properties['links'] - - def fetch(self): - """ - Fetch a ServiceInstance - - :returns: Fetched ServiceInstance - :rtype: twilio.rest.preview.acc_security.service.ServiceInstance - """ - return self._proxy.fetch() - - def update(self, name=values.unset, code_length=values.unset): - """ - Update the ServiceInstance - - :param unicode name: Friendly name of the service - :param unicode code_length: Length of verification code. Valid values are 4-10 - - :returns: Updated ServiceInstance - :rtype: twilio.rest.preview.acc_security.service.ServiceInstance - """ - return self._proxy.update(name=name, code_length=code_length, ) - - @property - def verifications(self): - """ - Access the verifications - - :returns: twilio.rest.preview.acc_security.service.verification.VerificationList - :rtype: twilio.rest.preview.acc_security.service.verification.VerificationList - """ - return self._proxy.verifications - - @property - def verification_checks(self): - """ - Access the verification_checks - - :returns: twilio.rest.preview.acc_security.service.verification_check.VerificationCheckList - :rtype: twilio.rest.preview.acc_security.service.verification_check.VerificationCheckList - """ - return self._proxy.verification_checks - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/acc_security/service/verification.py b/twilio/rest/preview/acc_security/service/verification.py deleted file mode 100644 index eefc46271f..0000000000 --- a/twilio/rest/preview/acc_security/service/verification.py +++ /dev/null @@ -1,224 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import values -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.page import Page - - -class VerificationList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid): - """ - Initialize the VerificationList - - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - - :returns: twilio.rest.preview.acc_security.service.verification.VerificationList - :rtype: twilio.rest.preview.acc_security.service.verification.VerificationList - """ - super(VerificationList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Verifications'.format(**self._solution) - - def create(self, to, channel, custom_message=values.unset): - """ - Create a new VerificationInstance - - :param unicode to: To phonenumber - :param unicode channel: sms or call - :param unicode custom_message: A custom message for this verification - - :returns: Newly created VerificationInstance - :rtype: twilio.rest.preview.acc_security.service.verification.VerificationInstance - """ - data = values.of({'To': to, 'Channel': channel, 'CustomMessage': custom_message, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return VerificationInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class VerificationPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the VerificationPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Service Sid. - - :returns: twilio.rest.preview.acc_security.service.verification.VerificationPage - :rtype: twilio.rest.preview.acc_security.service.verification.VerificationPage - """ - super(VerificationPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of VerificationInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.acc_security.service.verification.VerificationInstance - :rtype: twilio.rest.preview.acc_security.service.verification.VerificationInstance - """ - return VerificationInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class VerificationInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - class Channel(object): - SMS = "sms" - CALL = "call" - - def __init__(self, version, payload, service_sid): - """ - Initialize the VerificationInstance - - :returns: twilio.rest.preview.acc_security.service.verification.VerificationInstance - :rtype: twilio.rest.preview.acc_security.service.verification.VerificationInstance - """ - super(VerificationInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'service_sid': payload['service_sid'], - 'account_sid': payload['account_sid'], - 'to': payload['to'], - 'channel': payload['channel'], - 'status': payload['status'], - 'valid': payload['valid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - } - - # Context - self._context = None - self._solution = {'service_sid': service_sid, } - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Verification. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def service_sid(self): - """ - :returns: Service Sid. - :rtype: unicode - """ - return self._properties['service_sid'] - - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def to(self): - """ - :returns: To phonenumber - :rtype: unicode - """ - return self._properties['to'] - - @property - def channel(self): - """ - :returns: sms or call - :rtype: VerificationInstance.Channel - """ - return self._properties['channel'] - - @property - def status(self): - """ - :returns: pending, approved, denied or expired - :rtype: unicode - """ - return self._properties['status'] - - @property - def valid(self): - """ - :returns: successful verification - :rtype: bool - """ - return self._properties['valid'] - - @property - def date_created(self): - """ - :returns: The date this Verification was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date this Verification was updated - :rtype: datetime - """ - return self._properties['date_updated'] - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/preview/acc_security/service/verification_check.py b/twilio/rest/preview/acc_security/service/verification_check.py deleted file mode 100644 index d7399879dc..0000000000 --- a/twilio/rest/preview/acc_security/service/verification_check.py +++ /dev/null @@ -1,223 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import values -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.page import Page - - -class VerificationCheckList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid): - """ - Initialize the VerificationCheckList - - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - - :returns: twilio.rest.preview.acc_security.service.verification_check.VerificationCheckList - :rtype: twilio.rest.preview.acc_security.service.verification_check.VerificationCheckList - """ - super(VerificationCheckList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/VerificationCheck'.format(**self._solution) - - def create(self, code, to=values.unset): - """ - Create a new VerificationCheckInstance - - :param unicode code: The verification string - :param unicode to: To phonenumber - - :returns: Newly created VerificationCheckInstance - :rtype: twilio.rest.preview.acc_security.service.verification_check.VerificationCheckInstance - """ - data = values.of({'Code': code, 'To': to, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return VerificationCheckInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class VerificationCheckPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the VerificationCheckPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Service Sid. - - :returns: twilio.rest.preview.acc_security.service.verification_check.VerificationCheckPage - :rtype: twilio.rest.preview.acc_security.service.verification_check.VerificationCheckPage - """ - super(VerificationCheckPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of VerificationCheckInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.acc_security.service.verification_check.VerificationCheckInstance - :rtype: twilio.rest.preview.acc_security.service.verification_check.VerificationCheckInstance - """ - return VerificationCheckInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class VerificationCheckInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - class Channel(object): - SMS = "sms" - CALL = "call" - - def __init__(self, version, payload, service_sid): - """ - Initialize the VerificationCheckInstance - - :returns: twilio.rest.preview.acc_security.service.verification_check.VerificationCheckInstance - :rtype: twilio.rest.preview.acc_security.service.verification_check.VerificationCheckInstance - """ - super(VerificationCheckInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'service_sid': payload['service_sid'], - 'account_sid': payload['account_sid'], - 'to': payload['to'], - 'channel': payload['channel'], - 'status': payload['status'], - 'valid': payload['valid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - } - - # Context - self._context = None - self._solution = {'service_sid': service_sid, } - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Verification Check. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def service_sid(self): - """ - :returns: Service Sid. - :rtype: unicode - """ - return self._properties['service_sid'] - - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def to(self): - """ - :returns: To phonenumber - :rtype: unicode - """ - return self._properties['to'] - - @property - def channel(self): - """ - :returns: sms or call - :rtype: VerificationCheckInstance.Channel - """ - return self._properties['channel'] - - @property - def status(self): - """ - :returns: pending, approved, denied or expired - :rtype: unicode - """ - return self._properties['status'] - - @property - def valid(self): - """ - :returns: successful verification - :rtype: bool - """ - return self._properties['valid'] - - @property - def date_created(self): - """ - :returns: The date this Verification Check was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date this Verification Check was updated - :rtype: datetime - """ - return self._properties['date_updated'] - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/preview/bulk_exports/__init__.py b/twilio/rest/preview/bulk_exports/__init__.py deleted file mode 100644 index cab14d8b87..0000000000 --- a/twilio/rest/preview/bulk_exports/__init__.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base.version import Version -from twilio.rest.preview.bulk_exports.export import ExportList -from twilio.rest.preview.bulk_exports.export_configuration import ExportConfigurationList - - -class BulkExports(Version): - - def __init__(self, domain): - """ - Initialize the BulkExports version of Preview - - :returns: BulkExports version of Preview - :rtype: twilio.rest.preview.bulk_exports.BulkExports.BulkExports - """ - super(BulkExports, self).__init__(domain) - self.version = 'BulkExports' - self._exports = None - self._export_configuration = None - - @property - def exports(self): - """ - :rtype: twilio.rest.preview.bulk_exports.export.ExportList - """ - if self._exports is None: - self._exports = ExportList(self) - return self._exports - - @property - def export_configuration(self): - """ - :rtype: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationList - """ - if self._export_configuration is None: - self._export_configuration = ExportConfigurationList(self) - return self._export_configuration - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/preview/bulk_exports/export/__init__.py b/twilio/rest/preview/bulk_exports/export/__init__.py deleted file mode 100644 index b43caf4b72..0000000000 --- a/twilio/rest/preview/bulk_exports/export/__init__.py +++ /dev/null @@ -1,262 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -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.page import Page -from twilio.rest.preview.bulk_exports.export.day import DayList - - -class ExportList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version): - """ - Initialize the ExportList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.preview.bulk_exports.export.ExportList - :rtype: twilio.rest.preview.bulk_exports.export.ExportList - """ - super(ExportList, self).__init__(version) - - # Path Solution - self._solution = {} - - def get(self, resource_type): - """ - Constructs a ExportContext - - :param resource_type: The resource_type - - :returns: twilio.rest.preview.bulk_exports.export.ExportContext - :rtype: twilio.rest.preview.bulk_exports.export.ExportContext - """ - return ExportContext(self._version, resource_type=resource_type, ) - - def __call__(self, resource_type): - """ - Constructs a ExportContext - - :param resource_type: The resource_type - - :returns: twilio.rest.preview.bulk_exports.export.ExportContext - :rtype: twilio.rest.preview.bulk_exports.export.ExportContext - """ - return ExportContext(self._version, resource_type=resource_type, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ExportPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the ExportPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.preview.bulk_exports.export.ExportPage - :rtype: twilio.rest.preview.bulk_exports.export.ExportPage - """ - super(ExportPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of ExportInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.bulk_exports.export.ExportInstance - :rtype: twilio.rest.preview.bulk_exports.export.ExportInstance - """ - return ExportInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ExportContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, resource_type): - """ - Initialize the ExportContext - - :param Version version: Version that contains the resource - :param resource_type: The resource_type - - :returns: twilio.rest.preview.bulk_exports.export.ExportContext - :rtype: twilio.rest.preview.bulk_exports.export.ExportContext - """ - super(ExportContext, self).__init__(version) - - # Path Solution - self._solution = {'resource_type': resource_type, } - self._uri = '/Exports/{resource_type}'.format(**self._solution) - - # Dependents - self._days = None - - def fetch(self): - """ - Fetch a ExportInstance - - :returns: Fetched ExportInstance - :rtype: twilio.rest.preview.bulk_exports.export.ExportInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return ExportInstance(self._version, payload, resource_type=self._solution['resource_type'], ) - - @property - def days(self): - """ - Access the days - - :returns: twilio.rest.preview.bulk_exports.export.day.DayList - :rtype: twilio.rest.preview.bulk_exports.export.day.DayList - """ - if self._days is None: - self._days = DayList(self._version, resource_type=self._solution['resource_type'], ) - return self._days - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class ExportInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, resource_type=None): - """ - Initialize the ExportInstance - - :returns: twilio.rest.preview.bulk_exports.export.ExportInstance - :rtype: twilio.rest.preview.bulk_exports.export.ExportInstance - """ - super(ExportInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'resource_type': payload['resource_type'], - 'url': payload['url'], - 'links': payload['links'], - } - - # Context - self._context = None - self._solution = {'resource_type': resource_type or self._properties['resource_type'], } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.bulk_exports.export.ExportContext - """ - if self._context is None: - self._context = ExportContext(self._version, resource_type=self._solution['resource_type'], ) - return self._context - - @property - def resource_type(self): - """ - :returns: The resource_type - :rtype: unicode - """ - return self._properties['resource_type'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def links(self): - """ - :returns: The links - :rtype: unicode - """ - return self._properties['links'] - - def fetch(self): - """ - Fetch a ExportInstance - - :returns: Fetched ExportInstance - :rtype: twilio.rest.preview.bulk_exports.export.ExportInstance - """ - return self._proxy.fetch() - - @property - def days(self): - """ - Access the days - - :returns: twilio.rest.preview.bulk_exports.export.day.DayList - :rtype: twilio.rest.preview.bulk_exports.export.day.DayList - """ - return self._proxy.days - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/bulk_exports/export/day.py b/twilio/rest/preview/bulk_exports/export/day.py deleted file mode 100644 index 62896fb93f..0000000000 --- a/twilio/rest/preview/bulk_exports/export/day.py +++ /dev/null @@ -1,235 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import values -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.page import Page - - -class DayList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, resource_type): - """ - Initialize the DayList - - :param Version version: Version that contains the resource - :param resource_type: The resource_type - - :returns: twilio.rest.preview.bulk_exports.export.day.DayList - :rtype: twilio.rest.preview.bulk_exports.export.day.DayList - """ - super(DayList, self).__init__(version) - - # Path Solution - self._solution = {'resource_type': resource_type, } - self._uri = '/Exports/{resource_type}/Days'.format(**self._solution) - - def stream(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.bulk_exports.export.day.DayInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.bulk_exports.export.day.DayInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of DayInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of DayInstance - :rtype: twilio.rest.preview.bulk_exports.export.day.DayPage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return DayPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of DayInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of DayInstance - :rtype: twilio.rest.preview.bulk_exports.export.day.DayPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return DayPage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class DayPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the DayPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param resource_type: The resource_type - - :returns: twilio.rest.preview.bulk_exports.export.day.DayPage - :rtype: twilio.rest.preview.bulk_exports.export.day.DayPage - """ - super(DayPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of DayInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.bulk_exports.export.day.DayInstance - :rtype: twilio.rest.preview.bulk_exports.export.day.DayInstance - """ - return DayInstance(self._version, payload, resource_type=self._solution['resource_type'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class DayInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, resource_type): - """ - Initialize the DayInstance - - :returns: twilio.rest.preview.bulk_exports.export.day.DayInstance - :rtype: twilio.rest.preview.bulk_exports.export.day.DayInstance - """ - super(DayInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'redirect_to': payload.get('redirect_to'), - 'day': payload.get('day'), - 'size': deserialize.integer(payload.get('size')), - 'resource_type': payload.get('resource_type'), - } - - # Context - self._context = None - self._solution = {'resource_type': resource_type, } - - @property - def redirect_to(self): - """ - :returns: The redirect_to - :rtype: unicode - """ - return self._properties['redirect_to'] - - @property - def day(self): - """ - :returns: The day - :rtype: unicode - """ - return self._properties['day'] - - @property - def size(self): - """ - :returns: The size - :rtype: unicode - """ - return self._properties['size'] - - @property - def resource_type(self): - """ - :returns: The resource_type - :rtype: unicode - """ - return self._properties['resource_type'] - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/preview/bulk_exports/export_configuration.py b/twilio/rest/preview/bulk_exports/export_configuration.py deleted file mode 100644 index e211d314f2..0000000000 --- a/twilio/rest/preview/bulk_exports/export_configuration.py +++ /dev/null @@ -1,301 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -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.page import Page - - -class ExportConfigurationList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version): - """ - Initialize the ExportConfigurationList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationList - :rtype: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationList - """ - super(ExportConfigurationList, self).__init__(version) - - # Path Solution - self._solution = {} - - def get(self, resource_type): - """ - Constructs a ExportConfigurationContext - - :param resource_type: The resource_type - - :returns: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationContext - :rtype: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationContext - """ - return ExportConfigurationContext(self._version, resource_type=resource_type, ) - - def __call__(self, resource_type): - """ - Constructs a ExportConfigurationContext - - :param resource_type: The resource_type - - :returns: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationContext - :rtype: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationContext - """ - return ExportConfigurationContext(self._version, resource_type=resource_type, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ExportConfigurationPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the ExportConfigurationPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationPage - :rtype: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationPage - """ - super(ExportConfigurationPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of ExportConfigurationInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationInstance - :rtype: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationInstance - """ - return ExportConfigurationInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ExportConfigurationContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, resource_type): - """ - Initialize the ExportConfigurationContext - - :param Version version: Version that contains the resource - :param resource_type: The resource_type - - :returns: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationContext - :rtype: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationContext - """ - super(ExportConfigurationContext, self).__init__(version) - - # Path Solution - self._solution = {'resource_type': resource_type, } - self._uri = '/Exports/{resource_type}/Configuration'.format(**self._solution) - - def fetch(self): - """ - Fetch a ExportConfigurationInstance - - :returns: Fetched ExportConfigurationInstance - :rtype: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return ExportConfigurationInstance( - self._version, - payload, - resource_type=self._solution['resource_type'], - ) - - def update(self, enabled=values.unset, webhook_url=values.unset, - webhook_method=values.unset): - """ - Update the ExportConfigurationInstance - - :param bool enabled: The enabled - :param unicode webhook_url: The webhook_url - :param unicode webhook_method: The webhook_method - - :returns: Updated ExportConfigurationInstance - :rtype: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationInstance - """ - data = values.of({'Enabled': enabled, 'WebhookUrl': webhook_url, 'WebhookMethod': webhook_method, }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return ExportConfigurationInstance( - self._version, - payload, - resource_type=self._solution['resource_type'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class ExportConfigurationInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, resource_type=None): - """ - Initialize the ExportConfigurationInstance - - :returns: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationInstance - :rtype: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationInstance - """ - super(ExportConfigurationInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'enabled': payload['enabled'], - 'webhook_url': payload['webhook_url'], - 'webhook_method': payload['webhook_method'], - 'resource_type': payload['resource_type'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = {'resource_type': resource_type or self._properties['resource_type'], } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationContext - """ - if self._context is None: - self._context = ExportConfigurationContext( - self._version, - resource_type=self._solution['resource_type'], - ) - return self._context - - @property - def enabled(self): - """ - :returns: The enabled - :rtype: bool - """ - return self._properties['enabled'] - - @property - def webhook_url(self): - """ - :returns: The webhook_url - :rtype: unicode - """ - return self._properties['webhook_url'] - - @property - def webhook_method(self): - """ - :returns: The webhook_method - :rtype: unicode - """ - return self._properties['webhook_method'] - - @property - def resource_type(self): - """ - :returns: The resource_type - :rtype: unicode - """ - return self._properties['resource_type'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch a ExportConfigurationInstance - - :returns: Fetched ExportConfigurationInstance - :rtype: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationInstance - """ - return self._proxy.fetch() - - def update(self, enabled=values.unset, webhook_url=values.unset, - webhook_method=values.unset): - """ - Update the ExportConfigurationInstance - - :param bool enabled: The enabled - :param unicode webhook_url: The webhook_url - :param unicode webhook_method: The webhook_method - - :returns: Updated ExportConfigurationInstance - :rtype: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationInstance - """ - return self._proxy.update(enabled=enabled, webhook_url=webhook_url, webhook_method=webhook_method, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/deployed_devices/__init__.py b/twilio/rest/preview/deployed_devices/__init__.py deleted file mode 100644 index 56d9d37ae6..0000000000 --- a/twilio/rest/preview/deployed_devices/__init__.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base.version import Version -from twilio.rest.preview.deployed_devices.fleet import FleetList - - -class DeployedDevices(Version): - - def __init__(self, domain): - """ - Initialize the DeployedDevices version of Preview - - :returns: DeployedDevices version of Preview - :rtype: twilio.rest.preview.deployed_devices.DeployedDevices.DeployedDevices - """ - super(DeployedDevices, self).__init__(domain) - self.version = 'DeployedDevices' - self._fleets = None - - @property - def fleets(self): - """ - :rtype: twilio.rest.preview.deployed_devices.fleet.FleetList - """ - if self._fleets is None: - self._fleets = FleetList(self) - return self._fleets - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/preview/deployed_devices/fleet/__init__.py b/twilio/rest/preview/deployed_devices/fleet/__init__.py deleted file mode 100644 index 59c27b8a1f..0000000000 --- a/twilio/rest/preview/deployed_devices/fleet/__init__.py +++ /dev/null @@ -1,545 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page -from twilio.rest.preview.deployed_devices.fleet.certificate import CertificateList -from twilio.rest.preview.deployed_devices.fleet.deployment import DeploymentList -from twilio.rest.preview.deployed_devices.fleet.device import DeviceList -from twilio.rest.preview.deployed_devices.fleet.key import KeyList - - -class FleetList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version): - """ - Initialize the FleetList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.preview.deployed_devices.fleet.FleetList - :rtype: twilio.rest.preview.deployed_devices.fleet.FleetList - """ - super(FleetList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Fleets'.format(**self._solution) - - def create(self, friendly_name=values.unset): - """ - Create a new FleetInstance - - :param unicode friendly_name: A human readable description for this Fleet. - - :returns: Newly created FleetInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.FleetInstance - """ - data = values.of({'FriendlyName': friendly_name, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return FleetInstance(self._version, payload, ) - - def stream(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.deployed_devices.fleet.FleetInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.deployed_devices.fleet.FleetInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of FleetInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of FleetInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.FleetPage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return FleetPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of FleetInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of FleetInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.FleetPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return FleetPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a FleetContext - - :param sid: A string that uniquely identifies the Fleet. - - :returns: twilio.rest.preview.deployed_devices.fleet.FleetContext - :rtype: twilio.rest.preview.deployed_devices.fleet.FleetContext - """ - return FleetContext(self._version, sid=sid, ) - - def __call__(self, sid): - """ - Constructs a FleetContext - - :param sid: A string that uniquely identifies the Fleet. - - :returns: twilio.rest.preview.deployed_devices.fleet.FleetContext - :rtype: twilio.rest.preview.deployed_devices.fleet.FleetContext - """ - return FleetContext(self._version, sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class FleetPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the FleetPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.preview.deployed_devices.fleet.FleetPage - :rtype: twilio.rest.preview.deployed_devices.fleet.FleetPage - """ - super(FleetPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of FleetInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.deployed_devices.fleet.FleetInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.FleetInstance - """ - return FleetInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class FleetContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, sid): - """ - Initialize the FleetContext - - :param Version version: Version that contains the resource - :param sid: A string that uniquely identifies the Fleet. - - :returns: twilio.rest.preview.deployed_devices.fleet.FleetContext - :rtype: twilio.rest.preview.deployed_devices.fleet.FleetContext - """ - super(FleetContext, self).__init__(version) - - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Fleets/{sid}'.format(**self._solution) - - # Dependents - self._devices = None - self._deployments = None - self._certificates = None - self._keys = None - - def fetch(self): - """ - Fetch a FleetInstance - - :returns: Fetched FleetInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.FleetInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return FleetInstance(self._version, payload, sid=self._solution['sid'], ) - - def delete(self): - """ - Deletes the FleetInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def update(self, friendly_name=values.unset, - default_deployment_sid=values.unset): - """ - Update the FleetInstance - - :param unicode friendly_name: A human readable description for this Fleet. - :param unicode default_deployment_sid: A default Deployment SID. - - :returns: Updated FleetInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.FleetInstance - """ - data = values.of({'FriendlyName': friendly_name, 'DefaultDeploymentSid': default_deployment_sid, }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return FleetInstance(self._version, payload, sid=self._solution['sid'], ) - - @property - def devices(self): - """ - Access the devices - - :returns: twilio.rest.preview.deployed_devices.fleet.device.DeviceList - :rtype: twilio.rest.preview.deployed_devices.fleet.device.DeviceList - """ - if self._devices is None: - self._devices = DeviceList(self._version, fleet_sid=self._solution['sid'], ) - return self._devices - - @property - def deployments(self): - """ - Access the deployments - - :returns: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentList - :rtype: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentList - """ - if self._deployments is None: - self._deployments = DeploymentList(self._version, fleet_sid=self._solution['sid'], ) - return self._deployments - - @property - def certificates(self): - """ - Access the certificates - - :returns: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateList - :rtype: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateList - """ - if self._certificates is None: - self._certificates = CertificateList(self._version, fleet_sid=self._solution['sid'], ) - return self._certificates - - @property - def keys(self): - """ - Access the keys - - :returns: twilio.rest.preview.deployed_devices.fleet.key.KeyList - :rtype: twilio.rest.preview.deployed_devices.fleet.key.KeyList - """ - if self._keys is None: - self._keys = KeyList(self._version, fleet_sid=self._solution['sid'], ) - return self._keys - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class FleetInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, sid=None): - """ - Initialize the FleetInstance - - :returns: twilio.rest.preview.deployed_devices.fleet.FleetInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.FleetInstance - """ - super(FleetInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'url': payload['url'], - 'unique_name': payload['unique_name'], - 'friendly_name': payload['friendly_name'], - 'account_sid': payload['account_sid'], - 'default_deployment_sid': payload['default_deployment_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'links': payload['links'], - } - - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.deployed_devices.fleet.FleetContext - """ - if self._context is None: - self._context = FleetContext(self._version, sid=self._solution['sid'], ) - return self._context - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Fleet. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def url(self): - """ - :returns: URL of this Fleet. - :rtype: unicode - """ - return self._properties['url'] - - @property - def unique_name(self): - """ - :returns: A unique, addressable name of this Fleet. - :rtype: unicode - """ - return self._properties['unique_name'] - - @property - def friendly_name(self): - """ - :returns: A human readable description for this Fleet. - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def account_sid(self): - """ - :returns: The unique SID that identifies this Account. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def default_deployment_sid(self): - """ - :returns: The unique SID that identifies this Fleet's default Deployment. - :rtype: unicode - """ - return self._properties['default_deployment_sid'] - - @property - def date_created(self): - """ - :returns: The date this Fleet was created. - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date this Fleet was updated. - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def links(self): - """ - :returns: Nested resource URLs. - :rtype: unicode - """ - return self._properties['links'] - - def fetch(self): - """ - Fetch a FleetInstance - - :returns: Fetched FleetInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.FleetInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the FleetInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def update(self, friendly_name=values.unset, - default_deployment_sid=values.unset): - """ - Update the FleetInstance - - :param unicode friendly_name: A human readable description for this Fleet. - :param unicode default_deployment_sid: A default Deployment SID. - - :returns: Updated FleetInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.FleetInstance - """ - return self._proxy.update( - friendly_name=friendly_name, - default_deployment_sid=default_deployment_sid, - ) - - @property - def devices(self): - """ - Access the devices - - :returns: twilio.rest.preview.deployed_devices.fleet.device.DeviceList - :rtype: twilio.rest.preview.deployed_devices.fleet.device.DeviceList - """ - return self._proxy.devices - - @property - def deployments(self): - """ - Access the deployments - - :returns: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentList - :rtype: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentList - """ - return self._proxy.deployments - - @property - def certificates(self): - """ - Access the certificates - - :returns: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateList - :rtype: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateList - """ - return self._proxy.certificates - - @property - def keys(self): - """ - Access the keys - - :returns: twilio.rest.preview.deployed_devices.fleet.key.KeyList - :rtype: twilio.rest.preview.deployed_devices.fleet.key.KeyList - """ - return self._proxy.keys - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/deployed_devices/fleet/certificate.py b/twilio/rest/preview/deployed_devices/fleet/certificate.py deleted file mode 100644 index c85401475a..0000000000 --- a/twilio/rest/preview/deployed_devices/fleet/certificate.py +++ /dev/null @@ -1,474 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page - - -class CertificateList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, fleet_sid): - """ - Initialize the CertificateList - - :param Version version: Version that contains the resource - :param fleet_sid: The unique identifier of the Fleet. - - :returns: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateList - :rtype: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateList - """ - super(CertificateList, self).__init__(version) - - # Path Solution - self._solution = {'fleet_sid': fleet_sid, } - self._uri = '/Fleets/{fleet_sid}/Certificates'.format(**self._solution) - - def create(self, certificate_data, friendly_name=values.unset, - device_sid=values.unset): - """ - Create a new CertificateInstance - - :param unicode certificate_data: The public certificate data. - :param unicode friendly_name: The human readable description for this Certificate. - :param unicode device_sid: The unique identifier of a Device to be authenticated. - - :returns: Newly created CertificateInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateInstance - """ - data = values.of({ - 'CertificateData': certificate_data, - 'FriendlyName': friendly_name, - 'DeviceSid': device_sid, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return CertificateInstance(self._version, payload, fleet_sid=self._solution['fleet_sid'], ) - - def stream(self, device_sid=values.unset, limit=None, page_size=None): - """ - Streams CertificateInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param unicode device_sid: Find all Certificates authenticating specified Device. - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.deployed_devices.fleet.certificate.CertificateInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(device_sid=device_sid, page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, device_sid=values.unset, limit=None, page_size=None): - """ - Lists CertificateInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param unicode device_sid: Find all Certificates authenticating specified Device. - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.deployed_devices.fleet.certificate.CertificateInstance] - """ - return list(self.stream(device_sid=device_sid, limit=limit, page_size=page_size, )) - - def page(self, device_sid=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of CertificateInstance records from the API. - Request is executed immediately - - :param unicode device_sid: Find all Certificates authenticating specified Device. - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of CertificateInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.certificate.CertificatePage - """ - params = values.of({ - 'DeviceSid': device_sid, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return CertificatePage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of CertificateInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of CertificateInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.certificate.CertificatePage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return CertificatePage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a CertificateContext - - :param sid: A string that uniquely identifies the Certificate. - - :returns: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateContext - :rtype: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateContext - """ - return CertificateContext(self._version, fleet_sid=self._solution['fleet_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a CertificateContext - - :param sid: A string that uniquely identifies the Certificate. - - :returns: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateContext - :rtype: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateContext - """ - return CertificateContext(self._version, fleet_sid=self._solution['fleet_sid'], sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class CertificatePage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the CertificatePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param fleet_sid: The unique identifier of the Fleet. - - :returns: twilio.rest.preview.deployed_devices.fleet.certificate.CertificatePage - :rtype: twilio.rest.preview.deployed_devices.fleet.certificate.CertificatePage - """ - super(CertificatePage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of CertificateInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateInstance - """ - return CertificateInstance(self._version, payload, fleet_sid=self._solution['fleet_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class CertificateContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, fleet_sid, sid): - """ - Initialize the CertificateContext - - :param Version version: Version that contains the resource - :param fleet_sid: The fleet_sid - :param sid: A string that uniquely identifies the Certificate. - - :returns: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateContext - :rtype: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateContext - """ - super(CertificateContext, self).__init__(version) - - # Path Solution - self._solution = {'fleet_sid': fleet_sid, 'sid': sid, } - self._uri = '/Fleets/{fleet_sid}/Certificates/{sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch a CertificateInstance - - :returns: Fetched CertificateInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return CertificateInstance( - self._version, - payload, - fleet_sid=self._solution['fleet_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the CertificateInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def update(self, friendly_name=values.unset, device_sid=values.unset): - """ - Update the CertificateInstance - - :param unicode friendly_name: The human readable description for this Certificate. - :param unicode device_sid: The unique identifier of a Device to be authenticated. - - :returns: Updated CertificateInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateInstance - """ - data = values.of({'FriendlyName': friendly_name, 'DeviceSid': device_sid, }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return CertificateInstance( - self._version, - payload, - fleet_sid=self._solution['fleet_sid'], - sid=self._solution['sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class CertificateInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, fleet_sid, sid=None): - """ - Initialize the CertificateInstance - - :returns: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateInstance - """ - super(CertificateInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'url': payload['url'], - 'friendly_name': payload['friendly_name'], - 'fleet_sid': payload['fleet_sid'], - 'account_sid': payload['account_sid'], - 'device_sid': payload['device_sid'], - 'thumbprint': payload['thumbprint'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - } - - # Context - self._context = None - self._solution = {'fleet_sid': fleet_sid, 'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: CertificateContext for this CertificateInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateContext - """ - if self._context is None: - self._context = CertificateContext( - self._version, - fleet_sid=self._solution['fleet_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Certificate. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def url(self): - """ - :returns: URL of this Certificate. - :rtype: unicode - """ - return self._properties['url'] - - @property - def friendly_name(self): - """ - :returns: A human readable description for this Certificate. - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def fleet_sid(self): - """ - :returns: The unique identifier of the Fleet. - :rtype: unicode - """ - return self._properties['fleet_sid'] - - @property - def account_sid(self): - """ - :returns: The unique SID that identifies this Account. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def device_sid(self): - """ - :returns: The unique identifier of a mapped Device. - :rtype: unicode - """ - return self._properties['device_sid'] - - @property - def thumbprint(self): - """ - :returns: A Certificate unique payload hash. - :rtype: unicode - """ - return self._properties['thumbprint'] - - @property - def date_created(self): - """ - :returns: The date this Certificate was created. - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date this Certificate was updated. - :rtype: datetime - """ - return self._properties['date_updated'] - - def fetch(self): - """ - Fetch a CertificateInstance - - :returns: Fetched CertificateInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the CertificateInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def update(self, friendly_name=values.unset, device_sid=values.unset): - """ - Update the CertificateInstance - - :param unicode friendly_name: The human readable description for this Certificate. - :param unicode device_sid: The unique identifier of a Device to be authenticated. - - :returns: Updated CertificateInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateInstance - """ - return self._proxy.update(friendly_name=friendly_name, device_sid=device_sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/deployed_devices/fleet/deployment.py b/twilio/rest/preview/deployed_devices/fleet/deployment.py deleted file mode 100644 index a0bb432c5f..0000000000 --- a/twilio/rest/preview/deployed_devices/fleet/deployment.py +++ /dev/null @@ -1,451 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page - - -class DeploymentList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, fleet_sid): - """ - Initialize the DeploymentList - - :param Version version: Version that contains the resource - :param fleet_sid: The unique identifier of the Fleet. - - :returns: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentList - :rtype: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentList - """ - super(DeploymentList, self).__init__(version) - - # Path Solution - self._solution = {'fleet_sid': fleet_sid, } - self._uri = '/Fleets/{fleet_sid}/Deployments'.format(**self._solution) - - def create(self, friendly_name=values.unset, sync_service_sid=values.unset): - """ - Create a new DeploymentInstance - - :param unicode friendly_name: A human readable description for this Deployment. - :param unicode sync_service_sid: The unique identifier of the Sync service instance. - - :returns: Newly created DeploymentInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentInstance - """ - data = values.of({'FriendlyName': friendly_name, 'SyncServiceSid': sync_service_sid, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return DeploymentInstance(self._version, payload, fleet_sid=self._solution['fleet_sid'], ) - - def stream(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of DeploymentInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of DeploymentInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentPage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return DeploymentPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of DeploymentInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of DeploymentInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return DeploymentPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a DeploymentContext - - :param sid: A string that uniquely identifies the Deployment. - - :returns: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentContext - :rtype: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentContext - """ - return DeploymentContext(self._version, fleet_sid=self._solution['fleet_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a DeploymentContext - - :param sid: A string that uniquely identifies the Deployment. - - :returns: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentContext - :rtype: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentContext - """ - return DeploymentContext(self._version, fleet_sid=self._solution['fleet_sid'], sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class DeploymentPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the DeploymentPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param fleet_sid: The unique identifier of the Fleet. - - :returns: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentPage - :rtype: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentPage - """ - super(DeploymentPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of DeploymentInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentInstance - """ - return DeploymentInstance(self._version, payload, fleet_sid=self._solution['fleet_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class DeploymentContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, fleet_sid, sid): - """ - Initialize the DeploymentContext - - :param Version version: Version that contains the resource - :param fleet_sid: The fleet_sid - :param sid: A string that uniquely identifies the Deployment. - - :returns: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentContext - :rtype: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentContext - """ - super(DeploymentContext, self).__init__(version) - - # Path Solution - self._solution = {'fleet_sid': fleet_sid, 'sid': sid, } - self._uri = '/Fleets/{fleet_sid}/Deployments/{sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch a DeploymentInstance - - :returns: Fetched DeploymentInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return DeploymentInstance( - self._version, - payload, - fleet_sid=self._solution['fleet_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the DeploymentInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def update(self, friendly_name=values.unset, sync_service_sid=values.unset): - """ - Update the DeploymentInstance - - :param unicode friendly_name: A human readable description for this Deployment. - :param unicode sync_service_sid: The unique identifier of the Sync service instance. - - :returns: Updated DeploymentInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentInstance - """ - data = values.of({'FriendlyName': friendly_name, 'SyncServiceSid': sync_service_sid, }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return DeploymentInstance( - self._version, - payload, - fleet_sid=self._solution['fleet_sid'], - sid=self._solution['sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class DeploymentInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, fleet_sid, sid=None): - """ - Initialize the DeploymentInstance - - :returns: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentInstance - """ - super(DeploymentInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'url': payload['url'], - 'friendly_name': payload['friendly_name'], - 'fleet_sid': payload['fleet_sid'], - 'account_sid': payload['account_sid'], - 'sync_service_sid': payload['sync_service_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - } - - # Context - self._context = None - self._solution = {'fleet_sid': fleet_sid, 'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentContext - """ - if self._context is None: - self._context = DeploymentContext( - self._version, - fleet_sid=self._solution['fleet_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Deployment. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def url(self): - """ - :returns: URL of this Deployment. - :rtype: unicode - """ - return self._properties['url'] - - @property - def friendly_name(self): - """ - :returns: A human readable description for this Deployment - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def fleet_sid(self): - """ - :returns: The unique identifier of the Fleet. - :rtype: unicode - """ - return self._properties['fleet_sid'] - - @property - def account_sid(self): - """ - :returns: The unique SID that identifies this Account. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def sync_service_sid(self): - """ - :returns: The unique identifier of the Sync service instance. - :rtype: unicode - """ - return self._properties['sync_service_sid'] - - @property - def date_created(self): - """ - :returns: The date this Deployment was created. - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date this Deployment was updated. - :rtype: datetime - """ - return self._properties['date_updated'] - - def fetch(self): - """ - Fetch a DeploymentInstance - - :returns: Fetched DeploymentInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the DeploymentInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def update(self, friendly_name=values.unset, sync_service_sid=values.unset): - """ - Update the DeploymentInstance - - :param unicode friendly_name: A human readable description for this Deployment. - :param unicode sync_service_sid: The unique identifier of the Sync service instance. - - :returns: Updated DeploymentInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentInstance - """ - return self._proxy.update(friendly_name=friendly_name, sync_service_sid=sync_service_sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/deployed_devices/fleet/device.py b/twilio/rest/preview/deployed_devices/fleet/device.py deleted file mode 100644 index a326b0290b..0000000000 --- a/twilio/rest/preview/deployed_devices/fleet/device.py +++ /dev/null @@ -1,522 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page - - -class DeviceList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, fleet_sid): - """ - Initialize the DeviceList - - :param Version version: Version that contains the resource - :param fleet_sid: The unique identifier of the Fleet. - - :returns: twilio.rest.preview.deployed_devices.fleet.device.DeviceList - :rtype: twilio.rest.preview.deployed_devices.fleet.device.DeviceList - """ - super(DeviceList, self).__init__(version) - - # Path Solution - self._solution = {'fleet_sid': fleet_sid, } - self._uri = '/Fleets/{fleet_sid}/Devices'.format(**self._solution) - - def create(self, unique_name=values.unset, friendly_name=values.unset, - identity=values.unset, deployment_sid=values.unset, - enabled=values.unset): - """ - Create a new DeviceInstance - - :param unicode unique_name: A unique, addressable name of this Device. - :param unicode friendly_name: A human readable description for this Device. - :param unicode identity: An identifier of the Device user. - :param unicode deployment_sid: The unique SID of the Deployment group. - :param bool enabled: The enabled - - :returns: Newly created DeviceInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.device.DeviceInstance - """ - data = values.of({ - 'UniqueName': unique_name, - 'FriendlyName': friendly_name, - 'Identity': identity, - 'DeploymentSid': deployment_sid, - 'Enabled': enabled, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return DeviceInstance(self._version, payload, fleet_sid=self._solution['fleet_sid'], ) - - def stream(self, deployment_sid=values.unset, limit=None, page_size=None): - """ - Streams DeviceInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param unicode deployment_sid: Find all Devices grouped under the specified Deployment. - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.deployed_devices.fleet.device.DeviceInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(deployment_sid=deployment_sid, page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, deployment_sid=values.unset, limit=None, page_size=None): - """ - Lists DeviceInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param unicode deployment_sid: Find all Devices grouped under the specified Deployment. - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.deployed_devices.fleet.device.DeviceInstance] - """ - return list(self.stream(deployment_sid=deployment_sid, limit=limit, page_size=page_size, )) - - def page(self, deployment_sid=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of DeviceInstance records from the API. - Request is executed immediately - - :param unicode deployment_sid: Find all Devices grouped under the specified Deployment. - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of DeviceInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.device.DevicePage - """ - params = values.of({ - 'DeploymentSid': deployment_sid, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return DevicePage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of DeviceInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of DeviceInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.device.DevicePage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return DevicePage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a DeviceContext - - :param sid: A string that uniquely identifies the Device. - - :returns: twilio.rest.preview.deployed_devices.fleet.device.DeviceContext - :rtype: twilio.rest.preview.deployed_devices.fleet.device.DeviceContext - """ - return DeviceContext(self._version, fleet_sid=self._solution['fleet_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a DeviceContext - - :param sid: A string that uniquely identifies the Device. - - :returns: twilio.rest.preview.deployed_devices.fleet.device.DeviceContext - :rtype: twilio.rest.preview.deployed_devices.fleet.device.DeviceContext - """ - return DeviceContext(self._version, fleet_sid=self._solution['fleet_sid'], sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class DevicePage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the DevicePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param fleet_sid: The unique identifier of the Fleet. - - :returns: twilio.rest.preview.deployed_devices.fleet.device.DevicePage - :rtype: twilio.rest.preview.deployed_devices.fleet.device.DevicePage - """ - super(DevicePage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of DeviceInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.deployed_devices.fleet.device.DeviceInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.device.DeviceInstance - """ - return DeviceInstance(self._version, payload, fleet_sid=self._solution['fleet_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class DeviceContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, fleet_sid, sid): - """ - Initialize the DeviceContext - - :param Version version: Version that contains the resource - :param fleet_sid: The fleet_sid - :param sid: A string that uniquely identifies the Device. - - :returns: twilio.rest.preview.deployed_devices.fleet.device.DeviceContext - :rtype: twilio.rest.preview.deployed_devices.fleet.device.DeviceContext - """ - super(DeviceContext, self).__init__(version) - - # Path Solution - self._solution = {'fleet_sid': fleet_sid, 'sid': sid, } - self._uri = '/Fleets/{fleet_sid}/Devices/{sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch a DeviceInstance - - :returns: Fetched DeviceInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.device.DeviceInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return DeviceInstance( - self._version, - payload, - fleet_sid=self._solution['fleet_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the DeviceInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def update(self, friendly_name=values.unset, identity=values.unset, - deployment_sid=values.unset, enabled=values.unset): - """ - Update the DeviceInstance - - :param unicode friendly_name: A human readable description for this Device. - :param unicode identity: An identifier of the Device user. - :param unicode deployment_sid: The unique SID of the Deployment group. - :param bool enabled: The enabled - - :returns: Updated DeviceInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.device.DeviceInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Identity': identity, - 'DeploymentSid': deployment_sid, - 'Enabled': enabled, - }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return DeviceInstance( - self._version, - payload, - fleet_sid=self._solution['fleet_sid'], - sid=self._solution['sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class DeviceInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, fleet_sid, sid=None): - """ - Initialize the DeviceInstance - - :returns: twilio.rest.preview.deployed_devices.fleet.device.DeviceInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.device.DeviceInstance - """ - super(DeviceInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'url': payload['url'], - 'unique_name': payload['unique_name'], - 'friendly_name': payload['friendly_name'], - 'fleet_sid': payload['fleet_sid'], - 'enabled': payload['enabled'], - 'account_sid': payload['account_sid'], - 'identity': payload['identity'], - 'deployment_sid': payload['deployment_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'date_authenticated': deserialize.iso8601_datetime(payload['date_authenticated']), - } - - # Context - self._context = None - self._solution = {'fleet_sid': fleet_sid, 'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: DeviceContext for this DeviceInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.device.DeviceContext - """ - if self._context is None: - self._context = DeviceContext( - self._version, - fleet_sid=self._solution['fleet_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Device. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def url(self): - """ - :returns: URL of this Device. - :rtype: unicode - """ - return self._properties['url'] - - @property - def unique_name(self): - """ - :returns: A unique, addressable name of this Device. - :rtype: unicode - """ - return self._properties['unique_name'] - - @property - def friendly_name(self): - """ - :returns: A human readable description for this Device - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def fleet_sid(self): - """ - :returns: The unique identifier of the Fleet. - :rtype: unicode - """ - return self._properties['fleet_sid'] - - @property - def enabled(self): - """ - :returns: Device enabled flag. - :rtype: bool - """ - return self._properties['enabled'] - - @property - def account_sid(self): - """ - :returns: The unique SID that identifies this Account. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def identity(self): - """ - :returns: An identifier of the Device user. - :rtype: unicode - """ - return self._properties['identity'] - - @property - def deployment_sid(self): - """ - :returns: The unique SID of the Deployment group. - :rtype: unicode - """ - return self._properties['deployment_sid'] - - @property - def date_created(self): - """ - :returns: The date this Device was created. - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date this Device was updated. - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def date_authenticated(self): - """ - :returns: The date this Device was authenticated. - :rtype: datetime - """ - return self._properties['date_authenticated'] - - def fetch(self): - """ - Fetch a DeviceInstance - - :returns: Fetched DeviceInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.device.DeviceInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the DeviceInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def update(self, friendly_name=values.unset, identity=values.unset, - deployment_sid=values.unset, enabled=values.unset): - """ - Update the DeviceInstance - - :param unicode friendly_name: A human readable description for this Device. - :param unicode identity: An identifier of the Device user. - :param unicode deployment_sid: The unique SID of the Deployment group. - :param bool enabled: The enabled - - :returns: Updated DeviceInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.device.DeviceInstance - """ - return self._proxy.update( - friendly_name=friendly_name, - identity=identity, - deployment_sid=deployment_sid, - enabled=enabled, - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/deployed_devices/fleet/key.py b/twilio/rest/preview/deployed_devices/fleet/key.py deleted file mode 100644 index 93881cafd0..0000000000 --- a/twilio/rest/preview/deployed_devices/fleet/key.py +++ /dev/null @@ -1,468 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page - - -class KeyList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, fleet_sid): - """ - Initialize the KeyList - - :param Version version: Version that contains the resource - :param fleet_sid: The unique identifier of the Fleet. - - :returns: twilio.rest.preview.deployed_devices.fleet.key.KeyList - :rtype: twilio.rest.preview.deployed_devices.fleet.key.KeyList - """ - super(KeyList, self).__init__(version) - - # Path Solution - self._solution = {'fleet_sid': fleet_sid, } - self._uri = '/Fleets/{fleet_sid}/Keys'.format(**self._solution) - - def create(self, friendly_name=values.unset, device_sid=values.unset): - """ - Create a new KeyInstance - - :param unicode friendly_name: The human readable description for this Key. - :param unicode device_sid: The unique identifier of a Key to be authenticated. - - :returns: Newly created KeyInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.key.KeyInstance - """ - data = values.of({'FriendlyName': friendly_name, 'DeviceSid': device_sid, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return KeyInstance(self._version, payload, fleet_sid=self._solution['fleet_sid'], ) - - def stream(self, device_sid=values.unset, limit=None, page_size=None): - """ - 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 unicode device_sid: Find all Keys authenticating specified Device. - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.deployed_devices.fleet.key.KeyInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(device_sid=device_sid, page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, device_sid=values.unset, limit=None, page_size=None): - """ - 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 unicode device_sid: Find all Keys authenticating specified Device. - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.deployed_devices.fleet.key.KeyInstance] - """ - return list(self.stream(device_sid=device_sid, limit=limit, page_size=page_size, )) - - def page(self, device_sid=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of KeyInstance records from the API. - Request is executed immediately - - :param unicode device_sid: Find all Keys authenticating specified Device. - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of KeyInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.key.KeyPage - """ - params = values.of({ - 'DeviceSid': device_sid, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return KeyPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of KeyInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of KeyInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.key.KeyPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return KeyPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a KeyContext - - :param sid: A string that uniquely identifies the Key. - - :returns: twilio.rest.preview.deployed_devices.fleet.key.KeyContext - :rtype: twilio.rest.preview.deployed_devices.fleet.key.KeyContext - """ - return KeyContext(self._version, fleet_sid=self._solution['fleet_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a KeyContext - - :param sid: A string that uniquely identifies the Key. - - :returns: twilio.rest.preview.deployed_devices.fleet.key.KeyContext - :rtype: twilio.rest.preview.deployed_devices.fleet.key.KeyContext - """ - return KeyContext(self._version, fleet_sid=self._solution['fleet_sid'], sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class KeyPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the KeyPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param fleet_sid: The unique identifier of the Fleet. - - :returns: twilio.rest.preview.deployed_devices.fleet.key.KeyPage - :rtype: twilio.rest.preview.deployed_devices.fleet.key.KeyPage - """ - super(KeyPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of KeyInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.deployed_devices.fleet.key.KeyInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.key.KeyInstance - """ - return KeyInstance(self._version, payload, fleet_sid=self._solution['fleet_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class KeyContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, fleet_sid, sid): - """ - Initialize the KeyContext - - :param Version version: Version that contains the resource - :param fleet_sid: The fleet_sid - :param sid: A string that uniquely identifies the Key. - - :returns: twilio.rest.preview.deployed_devices.fleet.key.KeyContext - :rtype: twilio.rest.preview.deployed_devices.fleet.key.KeyContext - """ - super(KeyContext, self).__init__(version) - - # Path Solution - self._solution = {'fleet_sid': fleet_sid, 'sid': sid, } - self._uri = '/Fleets/{fleet_sid}/Keys/{sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch a KeyInstance - - :returns: Fetched KeyInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.key.KeyInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return KeyInstance( - self._version, - payload, - fleet_sid=self._solution['fleet_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the KeyInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def update(self, friendly_name=values.unset, device_sid=values.unset): - """ - Update the KeyInstance - - :param unicode friendly_name: The human readable description for this Key. - :param unicode device_sid: The unique identifier of a Key to be authenticated. - - :returns: Updated KeyInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.key.KeyInstance - """ - data = values.of({'FriendlyName': friendly_name, 'DeviceSid': device_sid, }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return KeyInstance( - self._version, - payload, - fleet_sid=self._solution['fleet_sid'], - sid=self._solution['sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class KeyInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, fleet_sid, sid=None): - """ - Initialize the KeyInstance - - :returns: twilio.rest.preview.deployed_devices.fleet.key.KeyInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.key.KeyInstance - """ - super(KeyInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'url': payload['url'], - 'friendly_name': payload['friendly_name'], - 'fleet_sid': payload['fleet_sid'], - 'account_sid': payload['account_sid'], - 'device_sid': payload['device_sid'], - 'secret': payload['secret'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - } - - # Context - self._context = None - self._solution = {'fleet_sid': fleet_sid, 'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.deployed_devices.fleet.key.KeyContext - """ - if self._context is None: - self._context = KeyContext( - self._version, - fleet_sid=self._solution['fleet_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Key. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def url(self): - """ - :returns: URL of this Key. - :rtype: unicode - """ - return self._properties['url'] - - @property - def friendly_name(self): - """ - :returns: A human readable description for this Key. - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def fleet_sid(self): - """ - :returns: The unique identifier of the Fleet. - :rtype: unicode - """ - return self._properties['fleet_sid'] - - @property - def account_sid(self): - """ - :returns: The unique SID that identifies this Account. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def device_sid(self): - """ - :returns: The unique identifier of a mapped Device. - :rtype: unicode - """ - return self._properties['device_sid'] - - @property - def secret(self): - """ - :returns: The key secret. - :rtype: unicode - """ - return self._properties['secret'] - - @property - def date_created(self): - """ - :returns: The date this Key credential was created. - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date this Key credential was updated. - :rtype: datetime - """ - return self._properties['date_updated'] - - def fetch(self): - """ - Fetch a KeyInstance - - :returns: Fetched KeyInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.key.KeyInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the KeyInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def update(self, friendly_name=values.unset, device_sid=values.unset): - """ - Update the KeyInstance - - :param unicode friendly_name: The human readable description for this Key. - :param unicode device_sid: The unique identifier of a Key to be authenticated. - - :returns: Updated KeyInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.key.KeyInstance - """ - return self._proxy.update(friendly_name=friendly_name, device_sid=device_sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/hosted_numbers/__init__.py b/twilio/rest/preview/hosted_numbers/__init__.py index 7262d0d10d..7b3a767eef 100644 --- a/twilio/rest/preview/hosted_numbers/__init__.py +++ b/twilio/rest/preview/hosted_numbers/__init__.py @@ -1,53 +1,53 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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.rest.preview.hosted_numbers.authorization_document import AuthorizationDocumentList +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): + def __init__(self, domain: Domain): """ Initialize the HostedNumbers version of Preview - :returns: HostedNumbers version of Preview - :rtype: twilio.rest.preview.hosted_numbers.HostedNumbers.HostedNumbers + :param domain: The Twilio.preview domain """ - super(HostedNumbers, self).__init__(domain) - self.version = 'HostedNumbers' - self._authorization_documents = None - self._hosted_number_orders = None + super().__init__(domain, "HostedNumbers") + self._authorization_documents: Optional[AuthorizationDocumentList] = None + self._hosted_number_orders: Optional[HostedNumberOrderList] = None @property - def authorization_documents(self): - """ - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentList - """ + 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): - """ - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderList - """ + 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): + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py b/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py index d009184988..49d3d40da5 100644 --- a/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py +++ b/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py @@ -1,506 +1,755 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 - +from twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order import ( + DependentHostedNumberOrderList, +) -class AuthorizationDocumentList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - def __init__(self, version): - """ - Initialize the AuthorizationDocumentList +class AuthorizationDocumentInstance(InstanceResource): - :param Version version: Version that contains the resource + class Status(object): + OPENED = "opened" + SIGNING = "signing" + SIGNED = "signed" + CANCELED = "canceled" + FAILED = "failed" - :returns: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentList - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentList - """ - super(AuthorizationDocumentList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {} - self._uri = '/AuthorizationDocuments'.format(**self._solution) + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[AuthorizationDocumentContext] = None - def stream(self, email=values.unset, status=values.unset, limit=None, - page_size=None): + @property + def _proxy(self) -> "AuthorizationDocumentContext": """ - 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 unicode email: Email. - :param AuthorizationDocumentInstance.Status status: The Status of this AuthorizationDocument. - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance] + :returns: AuthorizationDocumentContext for this AuthorizationDocumentInstance """ - 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'], limits['page_limit']) + if self._context is None: + self._context = AuthorizationDocumentContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def list(self, email=values.unset, status=values.unset, limit=None, - page_size=None): + def fetch(self) -> "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. + Fetch the AuthorizationDocumentInstance - :param unicode email: Email. - :param AuthorizationDocumentInstance.Status status: The Status of this AuthorizationDocument. - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance] + :returns: The fetched AuthorizationDocumentInstance """ - return list(self.stream(email=email, status=status, limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, email=values.unset, status=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + async def fetch_async(self) -> "AuthorizationDocumentInstance": """ - Retrieve a single page of AuthorizationDocumentInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the AuthorizationDocumentInstance - :param unicode email: Email. - :param AuthorizationDocumentInstance.Status status: The Status of this AuthorizationDocument. - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of AuthorizationDocumentInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentPage + :returns: The fetched AuthorizationDocumentInstance """ - params = values.of({ - 'Email': email, - 'Status': status, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + return await self._proxy.fetch_async() - return AuthorizationDocumentPage(self._version, response, self._solution) - - def get_page(self, target_url): + 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": """ - Retrieve a specific page of AuthorizationDocumentInstance records from the API. - Request is executed immediately + Update the AuthorizationDocumentInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of AuthorizationDocumentInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentPage + :returns: The updated AuthorizationDocumentInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, ) - return AuthorizationDocumentPage(self._version, response, self._solution) - - def create(self, hosted_number_order_sids, address_sid, email, - cc_emails=values.unset): - """ - Create a new AuthorizationDocumentInstance - - :param unicode hosted_number_order_sids: A list of HostedNumberOrder sids. - :param unicode address_sid: Address sid. - :param unicode email: Email. - :param unicode cc_emails: A list of emails. - - :returns: Newly created AuthorizationDocumentInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.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), - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, + 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, ) - return AuthorizationDocumentInstance(self._version, payload, ) - - def get(self, sid): - """ - Constructs a AuthorizationDocumentContext - - :param sid: AuthorizationDocument sid. - - :returns: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentContext - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentContext - """ - return AuthorizationDocumentContext(self._version, sid=sid, ) - - def __call__(self, sid): + @property + def dependent_hosted_number_orders(self) -> DependentHostedNumberOrderList: """ - Constructs a AuthorizationDocumentContext - - :param sid: AuthorizationDocument sid. - - :returns: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentContext - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentContext + Access the dependent_hosted_number_orders """ - return AuthorizationDocumentContext(self._version, sid=sid, ) + return self._proxy.dependent_hosted_number_orders - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) -class AuthorizationDocumentPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ +class AuthorizationDocumentContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the AuthorizationDocumentPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the AuthorizationDocumentContext - :returns: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentPage - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentPage + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this AuthorizationDocument. """ - super(AuthorizationDocumentPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of AuthorizationDocumentInstance + self._solution = { + "sid": sid, + } + self._uri = "/AuthorizationDocuments/{sid}".format(**self._solution) - :param dict payload: Payload response from the API + self._dependent_hosted_number_orders: Optional[ + DependentHostedNumberOrderList + ] = None - :returns: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance + def fetch(self) -> AuthorizationDocumentInstance: """ - return AuthorizationDocumentInstance(self._version, payload, ) + Fetch the AuthorizationDocumentInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: The fetched AuthorizationDocumentInstance """ - return '' + headers = values.of({}) -class AuthorizationDocumentContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ + headers["Accept"] = "application/json" - def __init__(self, version, sid): - """ - Initialize the AuthorizationDocumentContext + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :param Version version: Version that contains the resource - :param sid: AuthorizationDocument sid. + return AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - :returns: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentContext - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentContext + async def fetch_async(self) -> AuthorizationDocumentInstance: """ - super(AuthorizationDocumentContext, self).__init__(version) + Asynchronous coroutine to fetch the AuthorizationDocumentInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/AuthorizationDocuments/{sid}'.format(**self._solution) - # Dependents - self._dependent_hosted_number_orders = None - - def fetch(self): + :returns: The fetched AuthorizationDocumentInstance """ - Fetch a AuthorizationDocumentInstance - :returns: Fetched AuthorizationDocumentInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance - """ - params = values.of({}) + headers = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], ) + return AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def update(self, hosted_number_order_sids=values.unset, - address_sid=values.unset, email=values.unset, cc_emails=values.unset, - status=values.unset): + 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 unicode hosted_number_order_sids: A list of HostedNumberOrder sids. - :param unicode address_sid: Address sid. - :param unicode email: Email. - :param unicode cc_emails: A list of emails. - :param AuthorizationDocumentInstance.Status status: The Status of this AuthorizationDocument. + :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({}) - :returns: Updated AuthorizationDocumentInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.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, - }) + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" payload = self._version.update( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) - return AuthorizationDocumentInstance(self._version, payload, sid=self._solution['sid'], ) + 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): + def dependent_hosted_number_orders(self) -> DependentHostedNumberOrderList: """ Access the dependent_hosted_number_orders - - :returns: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderList - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderList """ if self._dependent_hosted_number_orders is None: self._dependent_hosted_number_orders = DependentHostedNumberOrderList( self._version, - signing_document_sid=self._solution['sid'], + self._solution["sid"], ) return self._dependent_hosted_number_orders - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) -class AuthorizationDocumentInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ +class AuthorizationDocumentPage(Page): - class Status(object): - OPENED = "opened" - SIGNING = "signing" - SIGNED = "signed" - CANCELED = "canceled" - FAILED = "failed" + def get_instance(self, payload: Dict[str, Any]) -> AuthorizationDocumentInstance: + """ + Build an instance of AuthorizationDocumentInstance - def __init__(self, version, payload, sid=None): + :param payload: Payload response from the API """ - Initialize the AuthorizationDocumentInstance + return AuthorizationDocumentInstance(self._version, payload) - :returns: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance + def __repr__(self) -> str: """ - super(AuthorizationDocumentInstance, self).__init__(version) + Provide a friendly representation - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'address_sid': payload['address_sid'], - 'status': payload['status'], - 'email': payload['email'], - 'cc_emails': payload['cc_emails'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - 'links': payload['links'], - } + :returns: Machine friendly representation + """ + return "" - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context +class AuthorizationDocumentList(ListResource): - :returns: AuthorizationDocumentContext for this AuthorizationDocumentInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentContext + def __init__(self, version: Version): """ - if self._context is None: - self._context = AuthorizationDocumentContext(self._version, sid=self._solution['sid'], ) - return self._context + Initialize the AuthorizationDocumentList - @property - def sid(self): - """ - :returns: AuthorizationDocument sid. - :rtype: unicode - """ - return self._properties['sid'] + :param version: Version that contains the resource - @property - def address_sid(self): - """ - :returns: Address sid. - :rtype: unicode """ - return self._properties['address_sid'] + super().__init__(version) - @property - def status(self): - """ - :returns: The Status of this AuthorizationDocument. - :rtype: AuthorizationDocumentInstance.Status - """ - return self._properties['status'] + self._uri = "/AuthorizationDocuments" - @property - def email(self): + 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: """ - :returns: Email. - :rtype: unicode + 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 """ - return self._properties['email'] - @property - def cc_emails(self): + 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]: """ - :returns: A list of emails. - :rtype: unicode + 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 """ - return self._properties['cc_emails'] + limits = self._version.read_limits(limit, page_size) + page = self.page(email=email, status=status, page_size=limits["page_size"]) - @property - def date_created(self): + 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]: """ - :returns: The date this AuthorizationDocument was created. - :rtype: datetime + 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 """ - return self._properties['date_created'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + email=email, status=status, page_size=limits["page_size"] + ) - @property - def date_updated(self): + 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]: """ - :returns: The date this AuthorizationDocument was updated. - :rtype: datetime + 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]: """ - return self._properties['date_updated'] + 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. - @property - def url(self): + :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: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + data = values.of( + { + "Email": email, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def links(self): + headers = values.of({"Content-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 """ - :returns: The links - :rtype: unicode + 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: """ - return self._properties['links'] + 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 - def fetch(self): + :returns: Page of AuthorizationDocumentInstance """ - Fetch a AuthorizationDocumentInstance + response = self._version.domain.twilio.request("GET", target_url) + return AuthorizationDocumentPage(self._version, response) - :returns: Fetched AuthorizationDocumentInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance + async def get_page_async(self, target_url: str) -> AuthorizationDocumentPage: """ - return self._proxy.fetch() + 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 - def update(self, hosted_number_order_sids=values.unset, - address_sid=values.unset, email=values.unset, cc_emails=values.unset, - status=values.unset): + :returns: Page of AuthorizationDocumentInstance """ - Update the AuthorizationDocumentInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return AuthorizationDocumentPage(self._version, response) - :param unicode hosted_number_order_sids: A list of HostedNumberOrder sids. - :param unicode address_sid: Address sid. - :param unicode email: Email. - :param unicode cc_emails: A list of emails. - :param AuthorizationDocumentInstance.Status status: The Status of this AuthorizationDocument. + def get(self, sid: str) -> AuthorizationDocumentContext: + """ + Constructs a AuthorizationDocumentContext - :returns: Updated AuthorizationDocumentInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance + :param sid: A 34 character string that uniquely identifies this AuthorizationDocument. """ - return self._proxy.update( - hosted_number_order_sids=hosted_number_order_sids, - address_sid=address_sid, - email=email, - cc_emails=cc_emails, - status=status, - ) + return AuthorizationDocumentContext(self._version, sid=sid) - @property - def dependent_hosted_number_orders(self): + def __call__(self, sid: str) -> AuthorizationDocumentContext: """ - Access the dependent_hosted_number_orders + Constructs a AuthorizationDocumentContext - :returns: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderList - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderList + :param sid: A 34 character string that uniquely identifies this AuthorizationDocument. """ - return self._proxy.dependent_hosted_number_orders + return AuthorizationDocumentContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 index 35555a33b4..0ec58f8792 100644 --- 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 @@ -1,461 +1,477 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 DependentHostedNumberOrderList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, signing_document_sid): - """ - Initialize the DependentHostedNumberOrderList - - :param Version version: Version that contains the resource - :param signing_document_sid: LOA document sid. - - :returns: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderList - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderList - """ - super(DependentHostedNumberOrderList, self).__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=values.unset, phone_number=values.unset, - incoming_phone_number_sid=values.unset, friendly_name=values.unset, - unique_name=values.unset, limit=None, page_size=None): - """ - 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. +class DependentHostedNumberOrderInstance(InstanceResource): - :param DependentHostedNumberOrderInstance.Status status: The Status of this HostedNumberOrder. - :param unicode phone_number: An E164 formatted phone number. - :param unicode incoming_phone_number_sid: IncomingPhoneNumber sid. - :param unicode friendly_name: A human readable description of this resource. - :param unicode unique_name: A unique, developer assigned name of this HostedNumberOrder. - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + 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" - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderInstance] - """ - limits = self._version.read_limits(limit, page_size) + class VerificationType(object): + PHONE_CALL = "phone-call" + PHONE_BILL = "phone-bill" - 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'], + """ + :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" ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, status=values.unset, phone_number=values.unset, - incoming_phone_number_sid=values.unset, friendly_name=values.unset, - unique_name=values.unset, limit=None, page_size=None): - """ - 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: The Status of this HostedNumberOrder. - :param unicode phone_number: An E164 formatted phone number. - :param unicode incoming_phone_number_sid: IncomingPhoneNumber sid. - :param unicode friendly_name: A human readable description of this resource. - :param unicode unique_name: A unique, developer assigned name of this HostedNumberOrder. - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderInstance] - """ - 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, - )) - - def page(self, status=values.unset, phone_number=values.unset, - incoming_phone_number_sid=values.unset, friendly_name=values.unset, - unique_name=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of DependentHostedNumberOrderInstance records from the API. - Request is executed immediately - - :param DependentHostedNumberOrderInstance.Status status: The Status of this HostedNumberOrder. - :param unicode phone_number: An E164 formatted phone number. - :param unicode incoming_phone_number_sid: IncomingPhoneNumber sid. - :param unicode friendly_name: A human readable description of this resource. - :param unicode unique_name: A unique, developer assigned name of this HostedNumberOrder. - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of DependentHostedNumberOrderInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderPage - """ - params = 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, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + 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") ) - - return DependentHostedNumberOrderPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of DependentHostedNumberOrderInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of DependentHostedNumberOrderInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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" ) - return DependentHostedNumberOrderPage(self._version, response, self._solution) + self._solution = { + "signing_document_sid": signing_document_sid, + } - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) class DependentHostedNumberOrderPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the DependentHostedNumberOrderPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param signing_document_sid: LOA document sid. - - :returns: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderPage - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderPage - """ - super(DependentHostedNumberOrderPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - def get_instance(self, payload): + def get_instance( + self, payload: Dict[str, Any] + ) -> DependentHostedNumberOrderInstance: """ Build an instance of DependentHostedNumberOrderInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderInstance + :param payload: Payload response from the API """ return DependentHostedNumberOrderInstance( self._version, payload, - signing_document_sid=self._solution['signing_document_sid'], + signing_document_sid=self._solution["signing_document_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class DependentHostedNumberOrderInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ +class DependentHostedNumberOrderList(ListResource): - 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" + def __init__(self, version: Version, signing_document_sid: str): + """ + Initialize the DependentHostedNumberOrderList - class VerificationType(object): - PHONE_CALL = "phone-call" - PHONE_BILL = "phone-bill" + :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. - def __init__(self, version, payload, signing_document_sid): """ - Initialize the DependentHostedNumberOrderInstance + super().__init__(version) - :returns: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderInstance - """ - super(DependentHostedNumberOrderInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'incoming_phone_number_sid': payload['incoming_phone_number_sid'], - 'address_sid': payload['address_sid'], - 'signing_document_sid': payload['signing_document_sid'], - 'phone_number': payload['phone_number'], - 'capabilities': payload['capabilities'], - 'friendly_name': payload['friendly_name'], - 'unique_name': payload['unique_name'], - 'status': payload['status'], - 'failure_reason': payload['failure_reason'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'verification_attempts': deserialize.integer(payload['verification_attempts']), - 'email': payload['email'], - 'cc_emails': payload['cc_emails'], - 'verification_type': payload['verification_type'], - 'verification_document_sid': payload['verification_document_sid'], - 'extension': payload['extension'], - 'call_delay': deserialize.integer(payload['call_delay']), - 'verification_code': payload['verification_code'], - 'verification_call_sids': payload['verification_call_sids'], + # Path Solution + self._solution = { + "signing_document_sid": signing_document_sid, } + self._uri = "/AuthorizationDocuments/{signing_document_sid}/DependentHostedNumberOrders".format( + **self._solution + ) - # Context - self._context = None - self._solution = {'signing_document_sid': signing_document_sid, } - - @property - def sid(self): - """ - :returns: HostedNumberOrder sid. - :rtype: unicode + 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]: """ - return self._properties['sid'] + 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. - @property - def account_sid(self): - """ - :returns: Account sid. - :rtype: unicode - """ - return self._properties['account_sid'] + :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) - @property - def incoming_phone_number_sid(self): - """ - :returns: IncomingPhoneNumber sid. - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['incoming_phone_number_sid'] + 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"], + ) - @property - def address_sid(self): - """ - :returns: Address sid. - :rtype: unicode - """ - return self._properties['address_sid'] + 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. - @property - def signing_document_sid(self): - """ - :returns: LOA document sid. - :rtype: unicode - """ - return self._properties['signing_document_sid'] + :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) - @property - def phone_number(self): - """ - :returns: An E164 formatted phone number. - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['phone_number'] + 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"], + ) - @property - def capabilities(self): - """ - :returns: A mapping of phone number capabilities. - :rtype: unicode + 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]: """ - return self._properties['capabilities'] + Lists DependentHostedNumberOrderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def friendly_name(self): - """ - :returns: A human readable description of this resource. - :rtype: unicode - """ - return self._properties['friendly_name'] + :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, + ) + ) - @property - def unique_name(self): - """ - :returns: A unique, developer assigned name of this HostedNumberOrder. - :rtype: unicode - """ - return self._properties['unique_name'] + 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. - @property - def status(self): - """ - :returns: The Status of this HostedNumberOrder. - :rtype: DependentHostedNumberOrderInstance.Status + :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: """ - return self._properties['status'] + Retrieve a single page of DependentHostedNumberOrderInstance records from the API. + Request is executed immediately - @property - def failure_reason(self): - """ - :returns: Why a hosted_number_order reached status "action-required" - :rtype: unicode - """ - return self._properties['failure_reason'] + :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 - @property - def date_created(self): - """ - :returns: The date this HostedNumberOrder was created. - :rtype: datetime + :returns: Page of DependentHostedNumberOrderInstance """ - return self._properties['date_created'] + 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, + } + ) - @property - def date_updated(self): - """ - :returns: The date this HostedNumberOrder was updated. - :rtype: datetime - """ - return self._properties['date_updated'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def verification_attempts(self): - """ - :returns: The number of attempts made to verify ownership of the phone number. - :rtype: unicode - """ - return self._properties['verification_attempts'] + headers["Accept"] = "application/json" - @property - def email(self): - """ - :returns: Email. - :rtype: unicode - """ - return self._properties['email'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DependentHostedNumberOrderPage(self._version, response, self._solution) - @property - def cc_emails(self): - """ - :returns: A list of emails. - :rtype: unicode - """ - return self._properties['cc_emails'] + 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 - @property - def verification_type(self): - """ - :returns: The method used for verifying ownership of the number to be hosted. - :rtype: DependentHostedNumberOrderInstance.VerificationType - """ - return self._properties['verification_type'] + :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 - @property - def verification_document_sid(self): - """ - :returns: Verification Document Sid. - :rtype: unicode + :returns: Page of DependentHostedNumberOrderInstance """ - return self._properties['verification_document_sid'] + 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, + } + ) - @property - def extension(self): - """ - :returns: Phone extension to use for ownership verification call. - :rtype: unicode - """ - return self._properties['extension'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def call_delay(self): - """ - :returns: Seconds (0-30) to delay ownership verification call by. - :rtype: unicode - """ - return self._properties['call_delay'] + 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) - @property - def verification_code(self): + def get_page(self, target_url: str) -> DependentHostedNumberOrderPage: """ - :returns: The digits passed during the ownership verification call. - :rtype: unicode + 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 """ - return self._properties['verification_code'] + response = self._version.domain.twilio.request("GET", target_url) + return DependentHostedNumberOrderPage(self._version, response, self._solution) - @property - def verification_call_sids(self): + async def get_page_async(self, target_url: str) -> DependentHostedNumberOrderPage: """ - :returns: List of IDs for ownership verification calls. - :rtype: unicode + 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 """ - return self._properties['verification_call_sids'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return DependentHostedNumberOrderPage(self._version, response, self._solution) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/preview/hosted_numbers/hosted_number_order.py b/twilio/rest/preview/hosted_numbers/hosted_number_order.py index 3f3248c282..0c20af8791 100644 --- a/twilio/rest/preview/hosted_numbers/hosted_number_order.py +++ b/twilio/rest/preview/hosted_numbers/hosted_number_order.py @@ -1,717 +1,985 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 HostedNumberOrderList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ +class HostedNumberOrderInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the HostedNumberOrderList + 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" - :param Version version: Version that contains the resource + class VerificationType(object): + PHONE_CALL = "phone-call" + PHONE_BILL = "phone-bill" - :returns: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderList - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderList - """ - super(HostedNumberOrderList, self).__init__(version) + """ + :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" + ) - # Path Solution - self._solution = {} - self._uri = '/HostedNumberOrders'.format(**self._solution) + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[HostedNumberOrderContext] = None - def stream(self, status=values.unset, phone_number=values.unset, - incoming_phone_number_sid=values.unset, friendly_name=values.unset, - unique_name=values.unset, limit=None, page_size=None): + @property + def _proxy(self) -> "HostedNumberOrderContext": """ - 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. - :param unicode phone_number: An E164 formatted phone number. - :param unicode incoming_phone_number_sid: IncomingPhoneNumber sid. - :param unicode friendly_name: A human readable description of this resource. - :param unicode unique_name: A unique, developer assigned name of this HostedNumberOrder. - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderInstance] + :returns: HostedNumberOrderContext for this HostedNumberOrderInstance """ - 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'], limits['page_limit']) + if self._context is None: + self._context = HostedNumberOrderContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def list(self, status=values.unset, phone_number=values.unset, - incoming_phone_number_sid=values.unset, friendly_name=values.unset, - unique_name=values.unset, limit=None, page_size=None): + def delete(self) -> bool: """ - Lists HostedNumberOrderInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the HostedNumberOrderInstance - :param HostedNumberOrderInstance.Status status: The Status of this HostedNumberOrder. - :param unicode phone_number: An E164 formatted phone number. - :param unicode incoming_phone_number_sid: IncomingPhoneNumber sid. - :param unicode friendly_name: A human readable description of this resource. - :param unicode unique_name: A unique, developer assigned name of this HostedNumberOrder. - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderInstance] + :returns: True if delete succeeds, False otherwise """ - 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, - )) + return self._proxy.delete() - def page(self, status=values.unset, phone_number=values.unset, - incoming_phone_number_sid=values.unset, friendly_name=values.unset, - unique_name=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + async def delete_async(self) -> bool: """ - Retrieve a single page of HostedNumberOrderInstance records from the API. - Request is executed immediately - - :param HostedNumberOrderInstance.Status status: The Status of this HostedNumberOrder. - :param unicode phone_number: An E164 formatted phone number. - :param unicode incoming_phone_number_sid: IncomingPhoneNumber sid. - :param unicode friendly_name: A human readable description of this resource. - :param unicode unique_name: A unique, developer assigned name of this HostedNumberOrder. - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of HostedNumberOrderInstance - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderPage - """ - params = 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, - }) + Asynchronous coroutine that deletes the HostedNumberOrderInstance - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return HostedNumberOrderPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: True if delete succeeds, False otherwise """ - Retrieve a specific page of HostedNumberOrderInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page + return await self._proxy.delete_async() - :returns: Page of HostedNumberOrderInstance - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return HostedNumberOrderPage(self._version, response, self._solution) - - def create(self, phone_number, sms_capability, account_sid=values.unset, - friendly_name=values.unset, unique_name=values.unset, - cc_emails=values.unset, sms_url=values.unset, - sms_method=values.unset, sms_fallback_url=values.unset, - sms_fallback_method=values.unset, status_callback_url=values.unset, - status_callback_method=values.unset, - sms_application_sid=values.unset, address_sid=values.unset, - email=values.unset, verification_type=values.unset, - verification_document_sid=values.unset): - """ - Create a new HostedNumberOrderInstance - - :param unicode phone_number: An E164 formatted phone number. - :param bool sms_capability: Specify SMS capability to host. - :param unicode account_sid: Account Sid. - :param unicode friendly_name: A human readable description of this resource. - :param unicode unique_name: A unique, developer assigned name of this HostedNumberOrder. - :param unicode cc_emails: A list of emails. - :param unicode sms_url: SMS URL. - :param unicode sms_method: SMS Method. - :param unicode sms_fallback_url: SMS Fallback URL. - :param unicode sms_fallback_method: SMS Fallback Method. - :param unicode status_callback_url: Status Callback URL. - :param unicode status_callback_method: Status Callback Method. - :param unicode sms_application_sid: SMS Application Sid. - :param unicode address_sid: Address sid. - :param unicode email: Email. - :param HostedNumberOrderInstance.VerificationType verification_type: Verification Type. - :param unicode verification_document_sid: Verification Document Sid - - :returns: Newly created HostedNumberOrderInstance - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderInstance - """ - data = values.of({ - 'PhoneNumber': phone_number, - 'SmsCapability': 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, - }) + def fetch(self) -> "HostedNumberOrderInstance": + """ + Fetch the HostedNumberOrderInstance - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - return HostedNumberOrderInstance(self._version, payload, ) + :returns: The fetched HostedNumberOrderInstance + """ + return self._proxy.fetch() - def get(self, sid): + async def fetch_async(self) -> "HostedNumberOrderInstance": """ - Constructs a HostedNumberOrderContext + Asynchronous coroutine to fetch the HostedNumberOrderInstance - :param sid: HostedNumberOrder sid. - :returns: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderContext - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderContext + :returns: The fetched HostedNumberOrderInstance """ - return HostedNumberOrderContext(self._version, sid=sid, ) + return await self._proxy.fetch_async() - def __call__(self, 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": """ - Constructs a HostedNumberOrderContext + Update the HostedNumberOrderInstance - :param sid: HostedNumberOrder sid. + :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: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderContext - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderContext + :returns: The updated HostedNumberOrderInstance """ - return HostedNumberOrderContext(self._version, sid=sid, ) + 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, + ) - def __repr__(self): + 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 - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) -class HostedNumberOrderPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ +class HostedNumberOrderContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the HostedNumberOrderPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the HostedNumberOrderContext - :returns: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderPage - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderPage + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this HostedNumberOrder. """ - super(HostedNumberOrderPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/HostedNumberOrders/{sid}".format(**self._solution) - def get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of HostedNumberOrderInstance + Deletes the HostedNumberOrderInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderInstance - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderInstance + :returns: True if delete succeeds, False otherwise """ - return HostedNumberOrderInstance(self._version, payload, ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the HostedNumberOrderInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class HostedNumberOrderContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, sid): + def fetch(self) -> HostedNumberOrderInstance: """ - Initialize the HostedNumberOrderContext + Fetch the HostedNumberOrderInstance - :param Version version: Version that contains the resource - :param sid: HostedNumberOrder sid. - :returns: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderContext - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderContext + :returns: The fetched HostedNumberOrderInstance """ - super(HostedNumberOrderContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/HostedNumberOrders/{sid}'.format(**self._solution) + headers = values.of({}) - def fetch(self): - """ - Fetch a HostedNumberOrderInstance + headers["Accept"] = "application/json" - :returns: Fetched HostedNumberOrderInstance - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderInstance - """ - params = values.of({}) + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + return HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return HostedNumberOrderInstance(self._version, payload, sid=self._solution['sid'], ) - - def delete(self): + async def fetch_async(self) -> HostedNumberOrderInstance: """ - Deletes the HostedNumberOrderInstance + Asynchronous coroutine to fetch the HostedNumberOrderInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - def update(self, friendly_name=values.unset, unique_name=values.unset, - email=values.unset, cc_emails=values.unset, status=values.unset, - verification_code=values.unset, verification_type=values.unset, - verification_document_sid=values.unset, extension=values.unset, - call_delay=values.unset): + :returns: The fetched HostedNumberOrderInstance """ - Update the HostedNumberOrderInstance - :param unicode friendly_name: A human readable description of this resource. - :param unicode unique_name: A unique, developer assigned name of this HostedNumberOrder. - :param unicode email: Email. - :param unicode cc_emails: A list of emails. - :param HostedNumberOrderInstance.Status status: The Status of this HostedNumberOrder. - :param unicode verification_code: A verification code. - :param HostedNumberOrderInstance.VerificationType verification_type: Verification Type. - :param unicode verification_document_sid: Verification Document Sid - :param unicode extension: The extension - :param unicode call_delay: The call_delay - - :returns: Updated HostedNumberOrderInstance - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.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({}) - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], ) + return HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __repr__(self): + 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: """ - Provide a friendly representation + Update the HostedNumberOrderInstance - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + :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" -class HostedNumberOrderInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ + headers["Accept"] = "application/json" - 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" + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) - class VerificationType(object): - PHONE_CALL = "phone-call" - PHONE_BILL = "phone-bill" + return HostedNumberOrderInstance( + self._version, payload, sid=self._solution["sid"] + ) - def __init__(self, version, payload, sid=None): - """ - Initialize the HostedNumberOrderInstance - - :returns: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderInstance - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderInstance - """ - super(HostedNumberOrderInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'incoming_phone_number_sid': payload['incoming_phone_number_sid'], - 'address_sid': payload['address_sid'], - 'signing_document_sid': payload['signing_document_sid'], - 'phone_number': payload['phone_number'], - 'capabilities': payload['capabilities'], - 'friendly_name': payload['friendly_name'], - 'unique_name': payload['unique_name'], - 'status': payload['status'], - 'failure_reason': payload['failure_reason'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'verification_attempts': deserialize.integer(payload['verification_attempts']), - 'email': payload['email'], - 'cc_emails': payload['cc_emails'], - 'url': payload['url'], - 'verification_type': payload['verification_type'], - 'verification_document_sid': payload['verification_document_sid'], - 'extension': payload['extension'], - 'call_delay': deserialize.integer(payload['call_delay']), - 'verification_code': payload['verification_code'], - 'verification_call_sids': payload['verification_call_sids'], - } + 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({}) - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + headers["Accept"] = "application/json" - :returns: HostedNumberOrderContext for this HostedNumberOrderInstance - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderContext - """ - if self._context is None: - self._context = HostedNumberOrderContext(self._version, sid=self._solution['sid'], ) - return self._context + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def sid(self): - """ - :returns: HostedNumberOrder sid. - :rtype: unicode - """ - return self._properties['sid'] + return HostedNumberOrderInstance( + self._version, payload, sid=self._solution["sid"] + ) - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def incoming_phone_number_sid(self): - """ - :returns: IncomingPhoneNumber sid. - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['incoming_phone_number_sid'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) - @property - def address_sid(self): - """ - :returns: Address sid. - :rtype: unicode - """ - return self._properties['address_sid'] - @property - def signing_document_sid(self): - """ - :returns: LOA document sid. - :rtype: unicode - """ - return self._properties['signing_document_sid'] +class HostedNumberOrderPage(Page): - @property - def phone_number(self): + def get_instance(self, payload: Dict[str, Any]) -> HostedNumberOrderInstance: """ - :returns: An E164 formatted phone number. - :rtype: unicode - """ - return self._properties['phone_number'] + Build an instance of HostedNumberOrderInstance - @property - def capabilities(self): - """ - :returns: A mapping of phone number capabilities. - :rtype: unicode + :param payload: Payload response from the API """ - return self._properties['capabilities'] + return HostedNumberOrderInstance(self._version, payload) - @property - def friendly_name(self): + def __repr__(self) -> str: """ - :returns: A human readable description of this resource. - :rtype: unicode - """ - return self._properties['friendly_name'] + Provide a friendly representation - @property - def unique_name(self): - """ - :returns: A unique, developer assigned name of this HostedNumberOrder. - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['unique_name'] + return "" - @property - def status(self): - """ - :returns: The Status of this HostedNumberOrder. - :rtype: HostedNumberOrderInstance.Status - """ - return self._properties['status'] - @property - def failure_reason(self): - """ - :returns: Why a hosted_number_order reached status "action-required" - :rtype: unicode - """ - return self._properties['failure_reason'] +class HostedNumberOrderList(ListResource): - @property - def date_created(self): - """ - :returns: The date this HostedNumberOrder was created. - :rtype: datetime + def __init__(self, version: Version): """ - return self._properties['date_created'] + Initialize the HostedNumberOrderList - @property - def date_updated(self): - """ - :returns: The date this HostedNumberOrder was updated. - :rtype: datetime - """ - return self._properties['date_updated'] + :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"}) - @property - def verification_attempts(self): - """ - :returns: The number of attempts made to verify ownership of the phone number. - :rtype: unicode - """ - return self._properties['verification_attempts'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def email(self): - """ - :returns: Email. - :rtype: unicode - """ - return self._properties['email'] + headers["Accept"] = "application/json" - @property - def cc_emails(self): - """ - :returns: A list of emails. - :rtype: unicode - """ - return self._properties['cc_emails'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def url(self): - """ - :returns: The URL of this HostedNumberOrder. - :rtype: unicode - """ - return self._properties['url'] + 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"}) - @property - def verification_type(self): - """ - :returns: The method used for verifying ownership of the number to be hosted. - :rtype: HostedNumberOrderInstance.VerificationType - """ - return self._properties['verification_type'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def verification_document_sid(self): - """ - :returns: Verification Document Sid. - :rtype: unicode + 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]: """ - return self._properties['verification_document_sid'] + 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. - @property - def extension(self): + :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 """ - :returns: Phone extension to use for ownership verification call. - :rtype: unicode + 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]: """ - return self._properties['extension'] + 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. - @property - def call_delay(self): + :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 """ - :returns: Seconds (0-30) to delay ownership verification call by. - :rtype: unicode + 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]: """ - return self._properties['call_delay'] + Lists HostedNumberOrderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def verification_code(self): + :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: """ - :returns: The digits passed during the ownership verification call. - :rtype: unicode + 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 """ - return self._properties['verification_code'] + 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, + } + ) - @property - def verification_call_sids(self): + headers = values.of({"Content-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 """ - :returns: List of IDs for ownership verification calls. - :rtype: unicode + 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: """ - return self._properties['verification_call_sids'] + Retrieve a specific page of HostedNumberOrderInstance records from the API. + Request is executed immediately - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of HostedNumberOrderInstance """ - Fetch a HostedNumberOrderInstance + response = self._version.domain.twilio.request("GET", target_url) + return HostedNumberOrderPage(self._version, response) - :returns: Fetched HostedNumberOrderInstance - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderInstance + async def get_page_async(self, target_url: str) -> HostedNumberOrderPage: """ - return self._proxy.fetch() + 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 - def delete(self): + :returns: Page of HostedNumberOrderInstance """ - Deletes the HostedNumberOrderInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return HostedNumberOrderPage(self._version, response) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def get(self, sid: str) -> HostedNumberOrderContext: """ - return self._proxy.delete() + Constructs a HostedNumberOrderContext - def update(self, friendly_name=values.unset, unique_name=values.unset, - email=values.unset, cc_emails=values.unset, status=values.unset, - verification_code=values.unset, verification_type=values.unset, - verification_document_sid=values.unset, extension=values.unset, - call_delay=values.unset): + :param sid: A 34 character string that uniquely identifies this HostedNumberOrder. """ - Update the HostedNumberOrderInstance + return HostedNumberOrderContext(self._version, sid=sid) - :param unicode friendly_name: A human readable description of this resource. - :param unicode unique_name: A unique, developer assigned name of this HostedNumberOrder. - :param unicode email: Email. - :param unicode cc_emails: A list of emails. - :param HostedNumberOrderInstance.Status status: The Status of this HostedNumberOrder. - :param unicode verification_code: A verification code. - :param HostedNumberOrderInstance.VerificationType verification_type: Verification Type. - :param unicode verification_document_sid: Verification Document Sid - :param unicode extension: The extension - :param unicode call_delay: The call_delay + def __call__(self, sid: str) -> HostedNumberOrderContext: + """ + Constructs a HostedNumberOrderContext - :returns: Updated HostedNumberOrderInstance - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderInstance + :param sid: A 34 character string that uniquely identifies this HostedNumberOrder. """ - 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, - ) + return HostedNumberOrderContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/preview/marketplace/__init__.py b/twilio/rest/preview/marketplace/__init__.py index 4f6010c826..fcc99a4112 100644 --- a/twilio/rest/preview/marketplace/__init__.py +++ b/twilio/rest/preview/marketplace/__init__.py @@ -1,53 +1,51 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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): + def __init__(self, domain: Domain): """ Initialize the Marketplace version of Preview - :returns: Marketplace version of Preview - :rtype: twilio.rest.preview.marketplace.Marketplace.Marketplace + :param domain: The Twilio.preview domain """ - super(Marketplace, self).__init__(domain) - self.version = 'marketplace' - self._available_add_ons = None - self._installed_add_ons = None + super().__init__(domain, "marketplace") + self._available_add_ons: Optional[AvailableAddOnList] = None + self._installed_add_ons: Optional[InstalledAddOnList] = None @property - def available_add_ons(self): - """ - :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnList - """ + 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): - """ - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnList - """ + 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): + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/preview/marketplace/available_add_on/__init__.py b/twilio/rest/preview/marketplace/available_add_on/__init__.py index 0f42eb7233..e81ec649de 100644 --- a/twilio/rest/preview/marketplace/available_add_on/__init__.py +++ b/twilio/rest/preview/marketplace/available_add_on/__init__.py @@ -1,383 +1,438 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 - +from twilio.rest.preview.marketplace.available_add_on.available_add_on_extension import ( + AvailableAddOnExtensionList, +) -class AvailableAddOnList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - def __init__(self, version): - """ - Initialize the AvailableAddOnList +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") - :param Version version: Version that contains the resource + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[AvailableAddOnContext] = None - :returns: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnList - :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnList + @property + def _proxy(self) -> "AvailableAddOnContext": """ - super(AvailableAddOnList, self).__init__(version) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - # Path Solution - self._solution = {} - self._uri = '/AvailableAddOns'.format(**self._solution) + :returns: AvailableAddOnContext for this AvailableAddOnInstance + """ + if self._context is None: + self._context = AvailableAddOnContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def stream(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the AvailableAddOnInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.marketplace.available_add_on.AvailableAddOnInstance] + :returns: The fetched AvailableAddOnInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(page_size=limits['page_size'], ) + async def fetch_async(self) -> "AvailableAddOnInstance": + """ + Asynchronous coroutine to fetch the AvailableAddOnInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + return await self._proxy.fetch_async() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + @property + def extensions(self) -> AvailableAddOnExtensionList: + """ + Access the extensions + """ + return self._proxy.extensions - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.marketplace.available_add_on.AvailableAddOnInstance] + def __repr__(self) -> str: """ - return list(self.stream(limit=limit, page_size=page_size, )) + Provide a friendly representation - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + :returns: Machine friendly representation """ - Retrieve a single page of AvailableAddOnInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of AvailableAddOnInstance - :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnPage +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. """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + super().__init__(version) - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/AvailableAddOns/{sid}".format(**self._solution) - return AvailableAddOnPage(self._version, response, self._solution) + self._extensions: Optional[AvailableAddOnExtensionList] = None - def get_page(self, target_url): + def fetch(self) -> AvailableAddOnInstance: """ - Retrieve a specific page of AvailableAddOnInstance records from the API. - Request is executed immediately + Fetch the AvailableAddOnInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of AvailableAddOnInstance - :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnPage + :returns: The fetched AvailableAddOnInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return AvailableAddOnPage(self._version, response, self._solution) + headers = values.of({}) - def get(self, sid): - """ - Constructs a AvailableAddOnContext + headers["Accept"] = "application/json" - :param sid: The unique Available Add-on Sid + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnContext - :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnContext - """ - return AvailableAddOnContext(self._version, sid=sid, ) + return AvailableAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __call__(self, sid): + async def fetch_async(self) -> AvailableAddOnInstance: """ - Constructs a AvailableAddOnContext + Asynchronous coroutine to fetch the AvailableAddOnInstance - :param sid: The unique Available Add-on Sid - :returns: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnContext - :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnContext + :returns: The fetched AvailableAddOnInstance """ - return AvailableAddOnContext(self._version, sid=sid, ) - def __repr__(self): - """ - Provide a friendly representation + headers = values.of({}) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Accept"] = "application/json" + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) -class AvailableAddOnPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ + return AvailableAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __init__(self, version, response, solution): + @property + def extensions(self) -> AvailableAddOnExtensionList: + """ + Access the extensions """ - Initialize the AvailableAddOnPage + if self._extensions is None: + self._extensions = AvailableAddOnExtensionList( + self._version, + self._solution["sid"], + ) + return self._extensions - :param Version version: Version that contains the resource - :param Response response: Response from the API + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnPage - :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnPage + :returns: Machine friendly representation """ - super(AvailableAddOnPage, self).__init__(version, response) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Path Solution - self._solution = solution - def get_instance(self, payload): +class AvailableAddOnPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AvailableAddOnInstance: """ Build an instance of AvailableAddOnInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnInstance - :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnInstance + :param payload: Payload response from the API """ - return AvailableAddOnInstance(self._version, payload, ) + return AvailableAddOnInstance(self._version, payload) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class AvailableAddOnContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ +class AvailableAddOnList(ListResource): - def __init__(self, version, sid): + def __init__(self, version: Version): """ - Initialize the AvailableAddOnContext + Initialize the AvailableAddOnList - :param Version version: Version that contains the resource - :param sid: The unique Available Add-on Sid + :param version: Version that contains the resource - :returns: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnContext - :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnContext """ - super(AvailableAddOnContext, self).__init__(version) + super().__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/AvailableAddOns/{sid}'.format(**self._solution) + self._uri = "/AvailableAddOns" - # Dependents - self._extensions = None + 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) - def fetch(self): + :returns: Generator that will yield up to limit results """ - Fetch a AvailableAddOnInstance + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) - :returns: Fetched AvailableAddOnInstance - :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnInstance + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AvailableAddOnInstance]: """ - params = values.of({}) + 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. - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(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 AvailableAddOnInstance(self._version, payload, sid=self._solution['sid'], ) + return self._version.stream_async(page, limits["limit"]) - @property - def extensions(self): + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnInstance]: """ - Access the extensions + 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: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionList - :rtype: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionList + :returns: list that will contain up to limit results """ - if self._extensions is None: - self._extensions = AvailableAddOnExtensionList( - self._version, - available_add_on_sid=self._solution['sid'], + return list( + self.stream( + limit=limit, + page_size=page_size, ) - return self._extensions + ) - def __repr__(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnInstance]: """ - Provide a friendly representation + 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. - :returns: Machine friendly representation - :rtype: str + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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 -class AvailableAddOnInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - def __init__(self, version, payload, sid=None): + :returns: Page of AvailableAddOnInstance """ - Initialize the AvailableAddOnInstance + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnInstance - :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnInstance - """ - super(AvailableAddOnInstance, self).__init__(version) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'friendly_name': payload['friendly_name'], - 'description': payload['description'], - 'pricing_type': payload['pricing_type'], - 'configuration_schema': payload['configuration_schema'], - 'url': payload['url'], - 'links': payload['links'], - } + headers["Accept"] = "application/json" - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AvailableAddOnPage(self._version, response) - @property - def _proxy(self): + 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: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Asynchronously retrieve a single page of AvailableAddOnInstance records from the API. + Request is executed immediately - :returns: AvailableAddOnContext for this AvailableAddOnInstance - :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnContext - """ - if self._context is None: - self._context = AvailableAddOnContext(self._version, sid=self._solution['sid'], ) - return self._context + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Add-on - :rtype: unicode + :returns: Page of AvailableAddOnInstance """ - return self._properties['sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def friendly_name(self): - """ - :returns: A description of this Add-on - :rtype: unicode - """ - return self._properties['friendly_name'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def description(self): - """ - :returns: A short description of the Add-on functionality - :rtype: unicode - """ - return self._properties['description'] + headers["Accept"] = "application/json" - @property - def pricing_type(self): - """ - :returns: The way customers are charged for using this Add-on - :rtype: unicode - """ - return self._properties['pricing_type'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AvailableAddOnPage(self._version, response) - @property - def configuration_schema(self): + def get_page(self, target_url: str) -> AvailableAddOnPage: """ - :returns: The JSON Schema describing the Add-on's configuration - :rtype: dict - """ - return self._properties['configuration_schema'] + Retrieve a specific page of AvailableAddOnInstance records from the API. + Request is executed immediately - @property - def url(self): - """ - :returns: The url - :rtype: unicode + :param target_url: API-generated URL for the requested results page + + :returns: Page of AvailableAddOnInstance """ - return self._properties['url'] + response = self._version.domain.twilio.request("GET", target_url) + return AvailableAddOnPage(self._version, response) - @property - def links(self): + async def get_page_async(self, target_url: str) -> AvailableAddOnPage: """ - :returns: The links - :rtype: unicode + 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 """ - return self._properties['links'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return AvailableAddOnPage(self._version, response) - def fetch(self): + def get(self, sid: str) -> AvailableAddOnContext: """ - Fetch a AvailableAddOnInstance + Constructs a AvailableAddOnContext - :returns: Fetched AvailableAddOnInstance - :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnInstance + :param sid: The SID of the AvailableAddOn resource to fetch. """ - return self._proxy.fetch() + return AvailableAddOnContext(self._version, sid=sid) - @property - def extensions(self): + def __call__(self, sid: str) -> AvailableAddOnContext: """ - Access the extensions + Constructs a AvailableAddOnContext - :returns: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionList - :rtype: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionList + :param sid: The SID of the AvailableAddOn resource to fetch. """ - return self._proxy.extensions + return AvailableAddOnContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 index d6848a2345..4c05f4244d 100644 --- 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 @@ -1,372 +1,445 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 AvailableAddOnExtensionList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, available_add_on_sid): - """ - Initialize the AvailableAddOnExtensionList +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") - :param Version version: Version that contains the resource - :param available_add_on_sid: The available_add_on_sid + self._solution = { + "available_add_on_sid": available_add_on_sid, + "sid": sid or self.sid, + } + self._context: Optional[AvailableAddOnExtensionContext] = None - :returns: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionList - :rtype: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionList + @property + def _proxy(self) -> "AvailableAddOnExtensionContext": """ - super(AvailableAddOnExtensionList, self).__init__(version) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - # Path Solution - self._solution = {'available_add_on_sid': available_add_on_sid, } - self._uri = '/AvailableAddOns/{available_add_on_sid}/Extensions'.format(**self._solution) + :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 stream(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the AvailableAddOnExtensionInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionInstance] + :returns: The fetched AvailableAddOnExtensionInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(page_size=limits['page_size'], ) + async def fetch_async(self) -> "AvailableAddOnExtensionInstance": + """ + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + return await self._proxy.fetch_async() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionInstance] + def __repr__(self) -> str: """ - return list(self.stream(limit=limit, page_size=page_size, )) + Provide a friendly representation - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + :returns: Machine friendly representation """ - Retrieve a single page of AvailableAddOnExtensionInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of AvailableAddOnExtensionInstance - :rtype: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionPage +class AvailableAddOnExtensionContext(InstanceContext): + + def __init__(self, version: Version, available_add_on_sid: str, sid: str): """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the AvailableAddOnExtensionContext - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + :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) - return AvailableAddOnExtensionPage(self._version, response, self._solution) + # 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 get_page(self, target_url): + def fetch(self) -> AvailableAddOnExtensionInstance: """ - Retrieve a specific page of AvailableAddOnExtensionInstance records from the API. - Request is executed immediately + Fetch the AvailableAddOnExtensionInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of AvailableAddOnExtensionInstance - :rtype: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionPage + :returns: The fetched AvailableAddOnExtensionInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return AvailableAddOnExtensionPage(self._version, response, self._solution) + headers = values.of({}) - def get(self, sid): - """ - Constructs a AvailableAddOnExtensionContext + headers["Accept"] = "application/json" - :param sid: The unique Extension Sid + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionContext - :rtype: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionContext - """ - return AvailableAddOnExtensionContext( + return AvailableAddOnExtensionInstance( self._version, - available_add_on_sid=self._solution['available_add_on_sid'], - sid=sid, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], ) - def __call__(self, sid): + async def fetch_async(self) -> AvailableAddOnExtensionInstance: """ - Constructs a AvailableAddOnExtensionContext + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance - :param sid: The unique Extension Sid - :returns: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionContext - :rtype: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionContext + :returns: The fetched AvailableAddOnExtensionInstance """ - return AvailableAddOnExtensionContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AvailableAddOnExtensionInstance( self._version, - available_add_on_sid=self._solution['available_add_on_sid'], - sid=sid, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) class AvailableAddOnExtensionPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the AvailableAddOnExtensionPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param available_add_on_sid: The available_add_on_sid - :returns: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionPage - :rtype: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionPage - """ - super(AvailableAddOnExtensionPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): + def get_instance(self, payload: Dict[str, Any]) -> AvailableAddOnExtensionInstance: """ Build an instance of AvailableAddOnExtensionInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionInstance - :rtype: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionInstance + :param payload: Payload response from the API """ return AvailableAddOnExtensionInstance( self._version, payload, - available_add_on_sid=self._solution['available_add_on_sid'], + available_add_on_sid=self._solution["available_add_on_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class AvailableAddOnExtensionContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ +class AvailableAddOnExtensionList(ListResource): - def __init__(self, version, available_add_on_sid, sid): + def __init__(self, version: Version, available_add_on_sid: str): """ - Initialize the AvailableAddOnExtensionContext + Initialize the AvailableAddOnExtensionList - :param Version version: Version that contains the resource - :param available_add_on_sid: The available_add_on_sid - :param sid: The unique Extension Sid + :param version: Version that contains the resource + :param available_add_on_sid: The SID of the AvailableAddOn resource with the extensions to read. - :returns: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionContext - :rtype: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionContext """ - super(AvailableAddOnExtensionContext, self).__init__(version) + 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): - """ - Fetch a AvailableAddOnExtensionInstance + self._solution = { + "available_add_on_sid": available_add_on_sid, + } + self._uri = "/AvailableAddOns/{available_add_on_sid}/Extensions".format( + **self._solution + ) - :returns: Fetched AvailableAddOnExtensionInstance - :rtype: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionInstance + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AvailableAddOnExtensionInstance]: """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) + 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. - return AvailableAddOnExtensionInstance( - self._version, - payload, - available_add_on_sid=self._solution['available_add_on_sid'], - sid=self._solution['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) - def __repr__(self): + :returns: Generator that will yield up to limit results """ - Provide a friendly representation + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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. -class AvailableAddOnExtensionInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - def __init__(self, version, payload, available_add_on_sid, sid=None): + :returns: Generator that will yield up to limit results """ - Initialize the AvailableAddOnExtensionInstance + 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"]) - :returns: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionInstance - :rtype: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionInstance + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnExtensionInstance]: """ - super(AvailableAddOnExtensionInstance, self).__init__(version) + Lists AvailableAddOnExtensionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'available_add_on_sid': payload['available_add_on_sid'], - 'friendly_name': payload['friendly_name'], - 'product_name': payload['product_name'], - 'unique_name': payload['unique_name'], - 'url': payload['url'], - } + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - # Context - self._context = None - self._solution = { - 'available_add_on_sid': available_add_on_sid, - 'sid': sid or self._properties['sid'], - } + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def _proxy(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnExtensionInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: AvailableAddOnExtensionContext for this AvailableAddOnExtensionInstance - :rtype: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionContext + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - 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 [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, ) - return self._context + ] - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Extension - :rtype: unicode + 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: """ - return self._properties['sid'] + Retrieve a single page of AvailableAddOnExtensionInstance records from the API. + Request is executed immediately - @property - def available_add_on_sid(self): - """ - :returns: The available_add_on_sid - :rtype: unicode + :param page_token: PageToken provided by the API + :param page_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 """ - return self._properties['available_add_on_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def friendly_name(self): + headers = values.of({"Content-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: """ - :returns: A human-readable description of this Extension - :rtype: unicode + 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 """ - return self._properties['friendly_name'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def product_name(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: A human-readable description of the Extension's Product - :rtype: unicode + 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 """ - return self._properties['product_name'] + response = self._version.domain.twilio.request("GET", target_url) + return AvailableAddOnExtensionPage(self._version, response, self._solution) - @property - def unique_name(self): + async def get_page_async(self, target_url: str) -> AvailableAddOnExtensionPage: """ - :returns: The string that uniquely identifies this Extension - :rtype: unicode + 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 """ - return self._properties['unique_name'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return AvailableAddOnExtensionPage(self._version, response, self._solution) - @property - def url(self): + def get(self, sid: str) -> AvailableAddOnExtensionContext: """ - :returns: The url - :rtype: unicode + Constructs a AvailableAddOnExtensionContext + + :param sid: The SID of the AvailableAddOn Extension resource to fetch. """ - return self._properties['url'] + return AvailableAddOnExtensionContext( + self._version, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=sid, + ) - def fetch(self): + def __call__(self, sid: str) -> AvailableAddOnExtensionContext: """ - Fetch a AvailableAddOnExtensionInstance + Constructs a AvailableAddOnExtensionContext - :returns: Fetched AvailableAddOnExtensionInstance - :rtype: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionInstance + :param sid: The SID of the AvailableAddOn Extension resource to fetch. """ - return self._proxy.fetch() + return AvailableAddOnExtensionContext( + self._version, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/preview/marketplace/installed_add_on/__init__.py b/twilio/rest/preview/marketplace/installed_add_on/__init__.py index 7ff165932b..7f1fadc510 100644 --- a/twilio/rest/preview/marketplace/installed_add_on/__init__.py +++ b/twilio/rest/preview/marketplace/installed_add_on/__init__.py @@ -1,490 +1,671 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 - +from twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension import ( + InstalledAddOnExtensionList, +) -class InstalledAddOnList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - def __init__(self, version): - """ - Initialize the InstalledAddOnList +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") - :param Version version: Version that contains the resource + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[InstalledAddOnContext] = None - :returns: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnList - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnList + @property + def _proxy(self) -> "InstalledAddOnContext": """ - super(InstalledAddOnList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/InstalledAddOns'.format(**self._solution) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def create(self, available_add_on_sid, accept_terms_of_service, - configuration=values.unset, unique_name=values.unset): + :returns: InstalledAddOnContext for this InstalledAddOnInstance """ - Create a new InstalledAddOnInstance - - :param unicode available_add_on_sid: A string that uniquely identifies the Add-on to install - :param bool accept_terms_of_service: A boolean reflecting your acceptance of the Terms of Service - :param dict configuration: The JSON object representing the configuration - :param unicode unique_name: The string that uniquely identifies this Add-on installation + if self._context is None: + self._context = InstalledAddOnContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: Newly created InstalledAddOnInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnInstance + def delete(self) -> bool: """ - data = values.of({ - 'AvailableAddOnSid': available_add_on_sid, - 'AcceptTermsOfService': accept_terms_of_service, - 'Configuration': serialize.object(configuration), - 'UniqueName': unique_name, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + Deletes the InstalledAddOnInstance - return InstalledAddOnInstance(self._version, payload, ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the InstalledAddOnInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the InstalledAddOnInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnInstance] + :returns: The fetched InstalledAddOnInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_async(self) -> "InstalledAddOnInstance": """ - Retrieve a single page of InstalledAddOnInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the InstalledAddOnInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of InstalledAddOnInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnPage + :returns: The fetched InstalledAddOnInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_async() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return InstalledAddOnPage(self._version, response, self._solution) - - def get_page(self, target_url): + def update( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> "InstalledAddOnInstance": """ - Retrieve a specific page of InstalledAddOnInstance records from the API. - Request is executed immediately + Update the InstalledAddOnInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of InstalledAddOnInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnPage + :returns: The updated InstalledAddOnInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + configuration=configuration, + unique_name=unique_name, ) - return InstalledAddOnPage(self._version, response, self._solution) - - def get(self, sid): + async def update_async( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> "InstalledAddOnInstance": """ - Constructs a InstalledAddOnContext + Asynchronous coroutine to update the InstalledAddOnInstance - :param sid: The unique Installed Add-on Sid + :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: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnContext - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnContext + :returns: The updated InstalledAddOnInstance """ - return InstalledAddOnContext(self._version, sid=sid, ) + return await self._proxy.update_async( + configuration=configuration, + unique_name=unique_name, + ) - def __call__(self, sid): + @property + def extensions(self) -> InstalledAddOnExtensionList: """ - Constructs a InstalledAddOnContext - - :param sid: The unique Installed Add-on Sid - - :returns: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnContext - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnContext + Access the extensions """ - return InstalledAddOnContext(self._version, sid=sid, ) + return self._proxy.extensions - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class InstalledAddOnPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ +class InstalledAddOnContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the InstalledAddOnPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the InstalledAddOnContext - :returns: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnPage - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnPage + :param version: Version that contains the resource + :param sid: The SID of the InstalledAddOn resource to update. """ - super(InstalledAddOnPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/InstalledAddOns/{sid}".format(**self._solution) - def get_instance(self, payload): + self._extensions: Optional[InstalledAddOnExtensionList] = None + + def delete(self) -> bool: """ - Build an instance of InstalledAddOnInstance + Deletes the InstalledAddOnInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnInstance + :returns: True if delete succeeds, False otherwise """ - return InstalledAddOnInstance(self._version, payload, ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the InstalledAddOnInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class InstalledAddOnContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, sid): + def fetch(self) -> InstalledAddOnInstance: """ - Initialize the InstalledAddOnContext + Fetch the InstalledAddOnInstance - :param Version version: Version that contains the resource - :param sid: The unique Installed Add-on Sid - :returns: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnContext - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnContext + :returns: The fetched InstalledAddOnInstance """ - super(InstalledAddOnContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/InstalledAddOns/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._extensions = None + headers["Accept"] = "application/json" - def delete(self): - """ - Deletes the InstalledAddOnInstance + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + return InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def fetch(self): + async def fetch_async(self) -> InstalledAddOnInstance: """ - Fetch a InstalledAddOnInstance + Asynchronous coroutine to fetch the InstalledAddOnInstance - :returns: Fetched InstalledAddOnInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnInstance + + :returns: The fetched InstalledAddOnInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], ) + return InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def update(self, configuration=values.unset, unique_name=values.unset): + def update( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> InstalledAddOnInstance: """ Update the InstalledAddOnInstance - :param dict configuration: The JSON object representing the configuration - :param unicode unique_name: The string that uniquely identifies this Add-on installation + :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: Updated InstalledAddOnInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnInstance + :returns: The updated InstalledAddOnInstance """ - data = values.of({'Configuration': serialize.object(configuration), 'UniqueName': unique_name, }) + + 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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) - return InstalledAddOnInstance(self._version, payload, sid=self._solution['sid'], ) + 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): + def extensions(self) -> InstalledAddOnExtensionList: """ Access the extensions - - :returns: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionList - :rtype: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionList """ if self._extensions is None: self._extensions = InstalledAddOnExtensionList( self._version, - installed_add_on_sid=self._solution['sid'], + self._solution["sid"], ) return self._extensions - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class InstalledAddOnInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, sid=None): - """ - Initialize the InstalledAddOnInstance - - :returns: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnInstance - """ - super(InstalledAddOnInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'friendly_name': payload['friendly_name'], - 'description': payload['description'], - 'configuration': payload['configuration'], - 'unique_name': payload['unique_name'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - 'links': payload['links'], - } - - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } +class InstalledAddOnPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> InstalledAddOnInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of InstalledAddOnInstance - :returns: InstalledAddOnContext for this InstalledAddOnInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = InstalledAddOnContext(self._version, sid=self._solution['sid'], ) - return self._context + return InstalledAddOnInstance(self._version, payload) - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Add-on installation - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): + :returns: Machine friendly representation """ - :returns: The Account id that has installed this Add-on - :rtype: unicode + return "" + + +class InstalledAddOnList(ListResource): + + def __init__(self, version: Version): """ - return self._properties['account_sid'] + Initialize the InstalledAddOnList + + :param version: Version that contains the resource - @property - def friendly_name(self): """ - :returns: A description of this Add-on installation - :rtype: unicode + 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: """ - return self._properties['friendly_name'] + Create the InstalledAddOnInstance - @property - def description(self): + :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 """ - :returns: A short description of the Add-on functionality - :rtype: unicode + + 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: """ - return self._properties['description'] + Asynchronously create the InstalledAddOnInstance - @property - def configuration(self): + :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 """ - :returns: The JSON object representing the current configuration - :rtype: dict + + 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]: """ - return self._properties['configuration'] + 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. - @property - def unique_name(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The string that uniquely identifies this Add-on installation - :rtype: unicode + 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]: """ - return self._properties['unique_name'] + 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. - @property - def date_created(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The date this Add-on installation was created - :rtype: datetime + 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]: """ - return self._properties['date_created'] + Lists InstalledAddOnInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def date_updated(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The date this Add-on installation was last updated - :rtype: datetime + 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]: """ - return self._properties['date_updated'] + 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. - @property - def url(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The url - :rtype: unicode + 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: """ - return self._properties['url'] + Retrieve a single page of InstalledAddOnInstance records from the API. + Request is executed immediately - @property - def links(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The links - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['links'] + Asynchronously retrieve a single page of InstalledAddOnInstance records from the API. + Request is executed immediately - def delete(self): + :param page_token: PageToken provided by the API + :param page_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 """ - Deletes the InstalledAddOnInstance + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: True if delete succeeds, False otherwise - :rtype: bool + headers = values.of({"Content-Type": "application/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: """ - return self._proxy.delete() + Retrieve a specific page of InstalledAddOnInstance records from the API. + Request is executed immediately - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of InstalledAddOnInstance """ - Fetch a InstalledAddOnInstance + response = self._version.domain.twilio.request("GET", target_url) + return InstalledAddOnPage(self._version, response) - :returns: Fetched InstalledAddOnInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnInstance + async def get_page_async(self, target_url: str) -> InstalledAddOnPage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of InstalledAddOnInstance records from the API. + Request is executed immediately - def update(self, configuration=values.unset, unique_name=values.unset): + :param target_url: API-generated URL for the requested results page + + :returns: Page of InstalledAddOnInstance """ - Update the InstalledAddOnInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return InstalledAddOnPage(self._version, response) - :param dict configuration: The JSON object representing the configuration - :param unicode unique_name: The string that uniquely identifies this Add-on installation + def get(self, sid: str) -> InstalledAddOnContext: + """ + Constructs a InstalledAddOnContext - :returns: Updated InstalledAddOnInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnInstance + :param sid: The SID of the InstalledAddOn resource to update. """ - return self._proxy.update(configuration=configuration, unique_name=unique_name, ) + return InstalledAddOnContext(self._version, sid=sid) - @property - def extensions(self): + def __call__(self, sid: str) -> InstalledAddOnContext: """ - Access the extensions + Constructs a InstalledAddOnContext - :returns: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionList - :rtype: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionList + :param sid: The SID of the InstalledAddOn resource to update. """ - return self._proxy.extensions + return InstalledAddOnContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 index c118f33795..e0574ee2fd 100644 --- 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 @@ -1,416 +1,533 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import values +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 InstalledAddOnExtensionList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ +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") - def __init__(self, version, installed_add_on_sid): + 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": """ - Initialize the InstalledAddOnExtensionList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param installed_add_on_sid: The installed_add_on_sid + :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 - :returns: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionList - :rtype: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionList + def fetch(self) -> "InstalledAddOnExtensionInstance": """ - super(InstalledAddOnExtensionList, self).__init__(version) + Fetch the InstalledAddOnExtensionInstance - # 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=None, page_size=None): + :returns: The fetched 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return self._proxy.fetch() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionInstance] + async def fetch_async(self) -> "InstalledAddOnExtensionInstance": """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched InstalledAddOnExtensionInstance + """ + return await self._proxy.fetch_async() - def list(self, limit=None, page_size=None): + def update(self, enabled: bool) -> "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. + Update the InstalledAddOnExtensionInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + :param enabled: Whether the Extension should be invoked. - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionInstance] + :returns: The updated InstalledAddOnExtensionInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.update( + enabled=enabled, + ) - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def update_async(self, enabled: bool) -> "InstalledAddOnExtensionInstance": """ - Retrieve a single page of InstalledAddOnExtensionInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the InstalledAddOnExtensionInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :param enabled: Whether the Extension should be invoked. - :returns: Page of InstalledAddOnExtensionInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionPage + :returns: The updated InstalledAddOnExtensionInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + return await self._proxy.update_async( + enabled=enabled, ) - return InstalledAddOnExtensionPage(self._version, response, self._solution) - - def get_page(self, target_url): + def __repr__(self) -> str: """ - Retrieve a specific page of InstalledAddOnExtensionInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page + Provide a friendly representation - :returns: Page of InstalledAddOnExtensionInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionPage + :returns: Machine friendly representation """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context ) - return InstalledAddOnExtensionPage(self._version, response, self._solution) - def get(self, sid): - """ - Constructs a InstalledAddOnExtensionContext +class InstalledAddOnExtensionContext(InstanceContext): - :param sid: The unique Extension Sid + def __init__(self, version: Version, installed_add_on_sid: str, sid: str): + """ + Initialize the InstalledAddOnExtensionContext - :returns: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionContext - :rtype: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.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. """ - return InstalledAddOnExtensionContext( - self._version, - installed_add_on_sid=self._solution['installed_add_on_sid'], - sid=sid, + 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 __call__(self, sid): + def fetch(self) -> InstalledAddOnExtensionInstance: """ - Constructs a InstalledAddOnExtensionContext + Fetch the InstalledAddOnExtensionInstance - :param sid: The unique Extension Sid - :returns: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionContext - :rtype: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionContext + :returns: The fetched InstalledAddOnExtensionInstance """ - return InstalledAddOnExtensionContext( - self._version, - installed_add_on_sid=self._solution['installed_add_on_sid'], - sid=sid, - ) - def __repr__(self): - """ - Provide a friendly representation + headers = values.of({}) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Accept"] = "application/json" + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) -class InstalledAddOnExtensionPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) - def __init__(self, version, response, solution): + async def fetch_async(self) -> InstalledAddOnExtensionInstance: """ - Initialize the InstalledAddOnExtensionPage + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param installed_add_on_sid: The installed_add_on_sid - :returns: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionPage - :rtype: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionPage + :returns: The fetched InstalledAddOnExtensionInstance """ - super(InstalledAddOnExtensionPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): - """ - Build an instance of InstalledAddOnExtensionInstance + headers["Accept"] = "application/json" - :param dict payload: Payload response from the API + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionInstance - """ return InstalledAddOnExtensionInstance( self._version, payload, - installed_add_on_sid=self._solution['installed_add_on_sid'], + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + def update(self, enabled: bool) -> InstalledAddOnExtensionInstance: """ - Provide a friendly representation + Update the InstalledAddOnExtensionInstance - :returns: Machine friendly representation - :rtype: str + :param enabled: Whether the Extension should be invoked. + + :returns: The updated InstalledAddOnExtensionInstance """ - return '' + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + } + ) + headers = values.of({}) -class InstalledAddOnExtensionContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, installed_add_on_sid, sid): - """ - Initialize the InstalledAddOnExtensionContext + headers["Accept"] = "application/json" - :param Version version: Version that contains the resource - :param installed_add_on_sid: The installed_add_on_sid - :param sid: The unique Extension Sid + 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"], + ) - :returns: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionContext - :rtype: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionContext + async def update_async(self, enabled: bool) -> InstalledAddOnExtensionInstance: """ - super(InstalledAddOnExtensionContext, self).__init__(version) + Asynchronous coroutine to update the InstalledAddOnExtensionInstance - # 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) + :param enabled: Whether the Extension should be invoked. - def fetch(self): + :returns: The updated InstalledAddOnExtensionInstance """ - Fetch a InstalledAddOnExtensionInstance - :returns: Fetched InstalledAddOnExtensionInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionInstance - """ - params = values.of({}) + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + } + ) + headers = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], ) - def update(self, enabled): + def __repr__(self) -> str: """ - Update the InstalledAddOnExtensionInstance - - :param bool enabled: A Boolean indicating if the Extension will be invoked + Provide a friendly representation - :returns: Updated InstalledAddOnExtensionInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionInstance + :returns: Machine friendly representation """ - data = values.of({'Enabled': enabled, }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".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'], - sid=self._solution['sid'], + installed_add_on_sid=self._solution["installed_add_on_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" -class InstalledAddOnExtensionInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ +class InstalledAddOnExtensionList(ListResource): - def __init__(self, version, payload, installed_add_on_sid, sid=None): + def __init__(self, version: Version, installed_add_on_sid: str): """ - Initialize the InstalledAddOnExtensionInstance + Initialize the InstalledAddOnExtensionList - :returns: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionInstance - """ - super(InstalledAddOnExtensionInstance, self).__init__(version) + :param version: Version that contains the resource + :param installed_add_on_sid: The SID of the InstalledAddOn resource with the extensions to read. - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'installed_add_on_sid': payload['installed_add_on_sid'], - 'friendly_name': payload['friendly_name'], - 'product_name': payload['product_name'], - 'unique_name': payload['unique_name'], - 'enabled': payload['enabled'], - 'url': payload['url'], - } + """ + super().__init__(version) - # Context - self._context = None + # Path Solution self._solution = { - 'installed_add_on_sid': installed_add_on_sid, - 'sid': sid or self._properties['sid'], + "installed_add_on_sid": installed_add_on_sid, } + self._uri = "/InstalledAddOns/{installed_add_on_sid}/Extensions".format( + **self._solution + ) - @property - def _proxy(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InstalledAddOnExtensionInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: InstalledAddOnExtensionContext for this InstalledAddOnExtensionInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionContext - """ - 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 + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - @property - def sid(self): + :returns: Generator that will yield up to limit results """ - :returns: A string that uniquely identifies this Extension - :rtype: unicode + 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]: """ - return self._properties['sid'] + 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. - @property - def installed_add_on_sid(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The installed_add_on_sid - :rtype: unicode + 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]: """ - return self._properties['installed_add_on_sid'] + Lists InstalledAddOnExtensionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def friendly_name(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: A human-readable description of this Extension - :rtype: unicode + 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]: """ - return self._properties['friendly_name'] + 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. - @property - def product_name(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: A human-readable description of the Extension's Product - :rtype: unicode + 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: """ - return self._properties['product_name'] + Retrieve a single page of InstalledAddOnExtensionInstance records from the API. + Request is executed immediately - @property - def unique_name(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The string that uniquely identifies this Extension - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['unique_name'] + Asynchronously retrieve a single page of InstalledAddOnExtensionInstance records from the API. + Request is executed immediately - @property - def enabled(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: A Boolean indicating if the Extension will be invoked - :rtype: bool + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['enabled'] + Retrieve a specific page of InstalledAddOnExtensionInstance records from the API. + Request is executed immediately - @property - def url(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of InstalledAddOnExtensionInstance """ - :returns: The url - :rtype: unicode + 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: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of InstalledAddOnExtensionInstance """ - Fetch a InstalledAddOnExtensionInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return InstalledAddOnExtensionPage(self._version, response, self._solution) - :returns: Fetched InstalledAddOnExtensionInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionInstance + def get(self, sid: str) -> InstalledAddOnExtensionContext: """ - return self._proxy.fetch() + Constructs a InstalledAddOnExtensionContext - def update(self, enabled): + :param sid: The SID of the InstalledAddOn Extension resource to update. """ - Update the InstalledAddOnExtensionInstance + return InstalledAddOnExtensionContext( + self._version, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=sid, + ) - :param bool enabled: A Boolean indicating if the Extension will be invoked + def __call__(self, sid: str) -> InstalledAddOnExtensionContext: + """ + Constructs a InstalledAddOnExtensionContext - :returns: Updated InstalledAddOnExtensionInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionInstance + :param sid: The SID of the InstalledAddOn Extension resource to update. """ - return self._proxy.update(enabled, ) + return InstalledAddOnExtensionContext( + self._version, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/preview/proxy/__init__.py b/twilio/rest/preview/proxy/__init__.py deleted file mode 100644 index e9e6ce7d2f..0000000000 --- a/twilio/rest/preview/proxy/__init__.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base.version import Version -from twilio.rest.preview.proxy.service import ServiceList - - -class Proxy(Version): - - def __init__(self, domain): - """ - Initialize the Proxy version of Preview - - :returns: Proxy version of Preview - :rtype: twilio.rest.preview.proxy.Proxy.Proxy - """ - super(Proxy, self).__init__(domain) - self.version = 'Proxy' - self._services = None - - @property - def services(self): - """ - :rtype: twilio.rest.preview.proxy.service.ServiceList - """ - if self._services is None: - self._services = ServiceList(self) - return self._services - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/preview/proxy/service/__init__.py b/twilio/rest/preview/proxy/service/__init__.py deleted file mode 100644 index 8fe255656e..0000000000 --- a/twilio/rest/preview/proxy/service/__init__.py +++ /dev/null @@ -1,535 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page -from twilio.rest.preview.proxy.service.phone_number import PhoneNumberList -from twilio.rest.preview.proxy.service.session import SessionList -from twilio.rest.preview.proxy.service.short_code import ShortCodeList - - -class ServiceList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version): - """ - Initialize the ServiceList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.preview.proxy.service.ServiceList - :rtype: twilio.rest.preview.proxy.service.ServiceList - """ - super(ServiceList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Services'.format(**self._solution) - - def stream(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.proxy.service.ServiceInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.proxy.service.ServiceInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of ServiceInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of ServiceInstance - :rtype: twilio.rest.preview.proxy.service.ServicePage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return ServicePage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of ServiceInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of ServiceInstance - :rtype: twilio.rest.preview.proxy.service.ServicePage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ServicePage(self._version, response, self._solution) - - def create(self, friendly_name=values.unset, auto_create=values.unset, - callback_url=values.unset): - """ - Create a new ServiceInstance - - :param unicode friendly_name: A human readable description of this resource - :param bool auto_create: Boolean flag specifying whether to auto-create threads. - :param unicode callback_url: URL Twilio will request for callbacks. - - :returns: Newly created ServiceInstance - :rtype: twilio.rest.preview.proxy.service.ServiceInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'AutoCreate': auto_create, - 'CallbackUrl': callback_url, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return ServiceInstance(self._version, payload, ) - - def get(self, sid): - """ - Constructs a ServiceContext - - :param sid: A string that uniquely identifies this Service. - - :returns: twilio.rest.preview.proxy.service.ServiceContext - :rtype: twilio.rest.preview.proxy.service.ServiceContext - """ - return ServiceContext(self._version, sid=sid, ) - - def __call__(self, sid): - """ - Constructs a ServiceContext - - :param sid: A string that uniquely identifies this Service. - - :returns: twilio.rest.preview.proxy.service.ServiceContext - :rtype: twilio.rest.preview.proxy.service.ServiceContext - """ - return ServiceContext(self._version, sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ServicePage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the ServicePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.preview.proxy.service.ServicePage - :rtype: twilio.rest.preview.proxy.service.ServicePage - """ - super(ServicePage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of ServiceInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.proxy.service.ServiceInstance - :rtype: twilio.rest.preview.proxy.service.ServiceInstance - """ - return ServiceInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ServiceContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, sid): - """ - Initialize the ServiceContext - - :param Version version: Version that contains the resource - :param sid: A string that uniquely identifies this Service. - - :returns: twilio.rest.preview.proxy.service.ServiceContext - :rtype: twilio.rest.preview.proxy.service.ServiceContext - """ - super(ServiceContext, self).__init__(version) - - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Services/{sid}'.format(**self._solution) - - # Dependents - self._sessions = None - self._phone_numbers = None - self._short_codes = None - - def fetch(self): - """ - Fetch a ServiceInstance - - :returns: Fetched ServiceInstance - :rtype: twilio.rest.preview.proxy.service.ServiceInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) - - def delete(self): - """ - Deletes the ServiceInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def update(self, friendly_name=values.unset, auto_create=values.unset, - callback_url=values.unset): - """ - Update the ServiceInstance - - :param unicode friendly_name: A human readable description of this resource - :param bool auto_create: Boolean flag specifying whether to auto-create threads. - :param unicode callback_url: URL Twilio will request for callbacks. - - :returns: Updated ServiceInstance - :rtype: twilio.rest.preview.proxy.service.ServiceInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'AutoCreate': auto_create, - 'CallbackUrl': callback_url, - }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) - - @property - def sessions(self): - """ - Access the sessions - - :returns: twilio.rest.preview.proxy.service.session.SessionList - :rtype: twilio.rest.preview.proxy.service.session.SessionList - """ - if self._sessions is None: - self._sessions = SessionList(self._version, service_sid=self._solution['sid'], ) - return self._sessions - - @property - def phone_numbers(self): - """ - Access the phone_numbers - - :returns: twilio.rest.preview.proxy.service.phone_number.PhoneNumberList - :rtype: twilio.rest.preview.proxy.service.phone_number.PhoneNumberList - """ - if self._phone_numbers is None: - self._phone_numbers = PhoneNumberList(self._version, service_sid=self._solution['sid'], ) - return self._phone_numbers - - @property - def short_codes(self): - """ - Access the short_codes - - :returns: twilio.rest.preview.proxy.service.short_code.ShortCodeList - :rtype: twilio.rest.preview.proxy.service.short_code.ShortCodeList - """ - if self._short_codes is None: - self._short_codes = ShortCodeList(self._version, service_sid=self._solution['sid'], ) - return self._short_codes - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class ServiceInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, sid=None): - """ - Initialize the ServiceInstance - - :returns: twilio.rest.preview.proxy.service.ServiceInstance - :rtype: twilio.rest.preview.proxy.service.ServiceInstance - """ - super(ServiceInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'friendly_name': payload['friendly_name'], - 'account_sid': payload['account_sid'], - 'auto_create': payload['auto_create'], - 'callback_url': payload['callback_url'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - 'links': payload['links'], - } - - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.proxy.service.ServiceContext - """ - if self._context is None: - self._context = ServiceContext(self._version, sid=self._solution['sid'], ) - return self._context - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Service. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def friendly_name(self): - """ - :returns: A human readable description of this resource - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def auto_create(self): - """ - :returns: Boolean flag specifying whether to auto-create threads. - :rtype: bool - """ - return self._properties['auto_create'] - - @property - def callback_url(self): - """ - :returns: URL Twilio will request for callbacks. - :rtype: unicode - """ - return self._properties['callback_url'] - - @property - def date_created(self): - """ - :returns: The date this Service was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date this Service was updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def url(self): - """ - :returns: The URL of this resource. - :rtype: unicode - """ - return self._properties['url'] - - @property - def links(self): - """ - :returns: Nested resource URLs. - :rtype: unicode - """ - return self._properties['links'] - - def fetch(self): - """ - Fetch a ServiceInstance - - :returns: Fetched ServiceInstance - :rtype: twilio.rest.preview.proxy.service.ServiceInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the ServiceInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def update(self, friendly_name=values.unset, auto_create=values.unset, - callback_url=values.unset): - """ - Update the ServiceInstance - - :param unicode friendly_name: A human readable description of this resource - :param bool auto_create: Boolean flag specifying whether to auto-create threads. - :param unicode callback_url: URL Twilio will request for callbacks. - - :returns: Updated ServiceInstance - :rtype: twilio.rest.preview.proxy.service.ServiceInstance - """ - return self._proxy.update( - friendly_name=friendly_name, - auto_create=auto_create, - callback_url=callback_url, - ) - - @property - def sessions(self): - """ - Access the sessions - - :returns: twilio.rest.preview.proxy.service.session.SessionList - :rtype: twilio.rest.preview.proxy.service.session.SessionList - """ - return self._proxy.sessions - - @property - def phone_numbers(self): - """ - Access the phone_numbers - - :returns: twilio.rest.preview.proxy.service.phone_number.PhoneNumberList - :rtype: twilio.rest.preview.proxy.service.phone_number.PhoneNumberList - """ - return self._proxy.phone_numbers - - @property - def short_codes(self): - """ - Access the short_codes - - :returns: twilio.rest.preview.proxy.service.short_code.ShortCodeList - :rtype: twilio.rest.preview.proxy.service.short_code.ShortCodeList - """ - return self._proxy.short_codes - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/proxy/service/phone_number.py b/twilio/rest/preview/proxy/service/phone_number.py deleted file mode 100644 index 0524e49a10..0000000000 --- a/twilio/rest/preview/proxy/service/phone_number.py +++ /dev/null @@ -1,422 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page - - -class PhoneNumberList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid): - """ - Initialize the PhoneNumberList - - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - - :returns: twilio.rest.preview.proxy.service.phone_number.PhoneNumberList - :rtype: twilio.rest.preview.proxy.service.phone_number.PhoneNumberList - """ - super(PhoneNumberList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/PhoneNumbers'.format(**self._solution) - - def create(self, sid): - """ - Create a new PhoneNumberInstance - - :param unicode sid: Delete by unique phone-number Sid - - :returns: Newly created PhoneNumberInstance - :rtype: twilio.rest.preview.proxy.service.phone_number.PhoneNumberInstance - """ - data = values.of({'Sid': sid, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return PhoneNumberInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def stream(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.proxy.service.phone_number.PhoneNumberInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.proxy.service.phone_number.PhoneNumberInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of PhoneNumberInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of PhoneNumberInstance - :rtype: twilio.rest.preview.proxy.service.phone_number.PhoneNumberPage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return PhoneNumberPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of PhoneNumberInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of PhoneNumberInstance - :rtype: twilio.rest.preview.proxy.service.phone_number.PhoneNumberPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return PhoneNumberPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a PhoneNumberContext - - :param sid: Fetch by unique phone-number Sid - - :returns: twilio.rest.preview.proxy.service.phone_number.PhoneNumberContext - :rtype: twilio.rest.preview.proxy.service.phone_number.PhoneNumberContext - """ - return PhoneNumberContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a PhoneNumberContext - - :param sid: Fetch by unique phone-number Sid - - :returns: twilio.rest.preview.proxy.service.phone_number.PhoneNumberContext - :rtype: twilio.rest.preview.proxy.service.phone_number.PhoneNumberContext - """ - return PhoneNumberContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class PhoneNumberPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the PhoneNumberPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Service Sid. - - :returns: twilio.rest.preview.proxy.service.phone_number.PhoneNumberPage - :rtype: twilio.rest.preview.proxy.service.phone_number.PhoneNumberPage - """ - super(PhoneNumberPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of PhoneNumberInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.proxy.service.phone_number.PhoneNumberInstance - :rtype: twilio.rest.preview.proxy.service.phone_number.PhoneNumberInstance - """ - return PhoneNumberInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class PhoneNumberContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid, sid): - """ - Initialize the PhoneNumberContext - - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: Fetch by unique phone-number Sid - - :returns: twilio.rest.preview.proxy.service.phone_number.PhoneNumberContext - :rtype: twilio.rest.preview.proxy.service.phone_number.PhoneNumberContext - """ - super(PhoneNumberContext, self).__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): - """ - Deletes the PhoneNumberInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def fetch(self): - """ - Fetch a PhoneNumberInstance - - :returns: Fetched PhoneNumberInstance - :rtype: twilio.rest.preview.proxy.service.phone_number.PhoneNumberInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return PhoneNumberInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class PhoneNumberInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the PhoneNumberInstance - - :returns: twilio.rest.preview.proxy.service.phone_number.PhoneNumberInstance - :rtype: twilio.rest.preview.proxy.service.phone_number.PhoneNumberInstance - """ - super(PhoneNumberInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'phone_number': payload['phone_number'], - 'country_code': payload['country_code'], - 'capabilities': payload['capabilities'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.proxy.service.phone_number.PhoneNumberContext - """ - if self._context is None: - self._context = PhoneNumberContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this resource - :rtype: unicode - """ - return self._properties['sid'] - - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def service_sid(self): - """ - :returns: Service Sid. - :rtype: unicode - """ - return self._properties['service_sid'] - - @property - def date_created(self): - """ - :returns: The date this resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date this resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def phone_number(self): - """ - :returns: The phone number - :rtype: unicode - """ - return self._properties['phone_number'] - - @property - def country_code(self): - """ - :returns: The ISO 3166-1 alpha-2 country code - :rtype: unicode - """ - return self._properties['country_code'] - - @property - def capabilities(self): - """ - :returns: Indicate if a phone can receive calls or messages - :rtype: unicode - """ - return self._properties['capabilities'] - - @property - def url(self): - """ - :returns: The URL of this resource. - :rtype: unicode - """ - return self._properties['url'] - - def delete(self): - """ - Deletes the PhoneNumberInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def fetch(self): - """ - Fetch a PhoneNumberInstance - - :returns: Fetched PhoneNumberInstance - :rtype: twilio.rest.preview.proxy.service.phone_number.PhoneNumberInstance - """ - return self._proxy.fetch() - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/proxy/service/session/__init__.py b/twilio/rest/preview/proxy/service/session/__init__.py deleted file mode 100644 index d8c05ff022..0000000000 --- a/twilio/rest/preview/proxy/service/session/__init__.py +++ /dev/null @@ -1,589 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import serialize -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.page import Page -from twilio.rest.preview.proxy.service.session.interaction import InteractionList -from twilio.rest.preview.proxy.service.session.participant import ParticipantList - - -class SessionList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid): - """ - Initialize the SessionList - - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - - :returns: twilio.rest.preview.proxy.service.session.SessionList - :rtype: twilio.rest.preview.proxy.service.session.SessionList - """ - super(SessionList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Sessions'.format(**self._solution) - - def stream(self, unique_name=values.unset, status=values.unset, limit=None, - page_size=None): - """ - 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 unicode unique_name: A unique, developer assigned name of this Session. - :param SessionInstance.Status status: The Status of this Session - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.proxy.service.session.SessionInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(unique_name=unique_name, status=status, page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, unique_name=values.unset, status=values.unset, limit=None, - page_size=None): - """ - 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 unicode unique_name: A unique, developer assigned name of this Session. - :param SessionInstance.Status status: The Status of this Session - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.proxy.service.session.SessionInstance] - """ - return list(self.stream(unique_name=unique_name, status=status, limit=limit, page_size=page_size, )) - - def page(self, unique_name=values.unset, status=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of SessionInstance records from the API. - Request is executed immediately - - :param unicode unique_name: A unique, developer assigned name of this Session. - :param SessionInstance.Status status: The Status of this Session - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of SessionInstance - :rtype: twilio.rest.preview.proxy.service.session.SessionPage - """ - params = values.of({ - 'UniqueName': unique_name, - 'Status': status, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return SessionPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of SessionInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of SessionInstance - :rtype: twilio.rest.preview.proxy.service.session.SessionPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return SessionPage(self._version, response, self._solution) - - def create(self, unique_name=values.unset, ttl=values.unset, - status=values.unset, participants=values.unset): - """ - Create a new SessionInstance - - :param unicode unique_name: A unique, developer assigned name of this Session. - :param unicode ttl: How long will this session stay open, in seconds. - :param SessionInstance.Status status: The Status of this Session - :param unicode participants: The participants - - :returns: Newly created SessionInstance - :rtype: twilio.rest.preview.proxy.service.session.SessionInstance - """ - data = values.of({ - 'UniqueName': unique_name, - 'Ttl': ttl, - 'Status': status, - 'Participants': serialize.map(participants, lambda e: e), - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return SessionInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def get(self, sid): - """ - Constructs a SessionContext - - :param sid: A string that uniquely identifies this Session. - - :returns: twilio.rest.preview.proxy.service.session.SessionContext - :rtype: twilio.rest.preview.proxy.service.session.SessionContext - """ - return SessionContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a SessionContext - - :param sid: A string that uniquely identifies this Session. - - :returns: twilio.rest.preview.proxy.service.session.SessionContext - :rtype: twilio.rest.preview.proxy.service.session.SessionContext - """ - return SessionContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SessionPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the SessionPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Service Sid. - - :returns: twilio.rest.preview.proxy.service.session.SessionPage - :rtype: twilio.rest.preview.proxy.service.session.SessionPage - """ - super(SessionPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of SessionInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.proxy.service.session.SessionInstance - :rtype: twilio.rest.preview.proxy.service.session.SessionInstance - """ - return SessionInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SessionContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid, sid): - """ - Initialize the SessionContext - - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param sid: A string that uniquely identifies this Session. - - :returns: twilio.rest.preview.proxy.service.session.SessionContext - :rtype: twilio.rest.preview.proxy.service.session.SessionContext - """ - super(SessionContext, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Sessions/{sid}'.format(**self._solution) - - # Dependents - self._interactions = None - self._participants = None - - def fetch(self): - """ - Fetch a SessionInstance - - :returns: Fetched SessionInstance - :rtype: twilio.rest.preview.proxy.service.session.SessionInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return SessionInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the SessionInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def update(self, unique_name=values.unset, ttl=values.unset, - status=values.unset, participants=values.unset): - """ - Update the SessionInstance - - :param unicode unique_name: A unique, developer assigned name of this Session. - :param unicode ttl: How long will this session stay open, in seconds. - :param SessionInstance.Status status: The Status of this Session - :param unicode participants: The participants - - :returns: Updated SessionInstance - :rtype: twilio.rest.preview.proxy.service.session.SessionInstance - """ - data = values.of({ - 'UniqueName': unique_name, - 'Ttl': ttl, - 'Status': status, - 'Participants': serialize.map(participants, lambda e: e), - }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return SessionInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - - @property - def interactions(self): - """ - Access the interactions - - :returns: twilio.rest.preview.proxy.service.session.interaction.InteractionList - :rtype: twilio.rest.preview.proxy.service.session.interaction.InteractionList - """ - if self._interactions is None: - self._interactions = InteractionList( - self._version, - service_sid=self._solution['service_sid'], - session_sid=self._solution['sid'], - ) - return self._interactions - - @property - def participants(self): - """ - Access the participants - - :returns: twilio.rest.preview.proxy.service.session.participant.ParticipantList - :rtype: twilio.rest.preview.proxy.service.session.participant.ParticipantList - """ - if self._participants is None: - self._participants = ParticipantList( - self._version, - service_sid=self._solution['service_sid'], - session_sid=self._solution['sid'], - ) - return self._participants - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class SessionInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - class Status(object): - IN_PROGESS = "in-progess" - COMPLETED = "completed" - - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the SessionInstance - - :returns: twilio.rest.preview.proxy.service.session.SessionInstance - :rtype: twilio.rest.preview.proxy.service.session.SessionInstance - """ - super(SessionInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'service_sid': payload['service_sid'], - 'account_sid': payload['account_sid'], - 'unique_name': payload['unique_name'], - 'ttl': deserialize.integer(payload['ttl']), - 'status': payload['status'], - 'start_time': deserialize.iso8601_datetime(payload['start_time']), - 'end_time': deserialize.iso8601_datetime(payload['end_time']), - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - 'links': payload['links'], - } - - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.proxy.service.session.SessionContext - """ - if self._context is None: - self._context = SessionContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Session. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def service_sid(self): - """ - :returns: Service Sid. - :rtype: unicode - """ - return self._properties['service_sid'] - - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def unique_name(self): - """ - :returns: A unique, developer assigned name of this Session. - :rtype: unicode - """ - return self._properties['unique_name'] - - @property - def ttl(self): - """ - :returns: How long will this session stay open, in seconds. - :rtype: unicode - """ - return self._properties['ttl'] - - @property - def status(self): - """ - :returns: The Status of this Session - :rtype: SessionInstance.Status - """ - return self._properties['status'] - - @property - def start_time(self): - """ - :returns: The date this Session was started - :rtype: datetime - """ - return self._properties['start_time'] - - @property - def end_time(self): - """ - :returns: The date this Session was ended - :rtype: datetime - """ - return self._properties['end_time'] - - @property - def date_created(self): - """ - :returns: The date this Session was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date this Session was updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def url(self): - """ - :returns: The URL of this Session. - :rtype: unicode - """ - return self._properties['url'] - - @property - def links(self): - """ - :returns: Nested resource URLs. - :rtype: unicode - """ - return self._properties['links'] - - def fetch(self): - """ - Fetch a SessionInstance - - :returns: Fetched SessionInstance - :rtype: twilio.rest.preview.proxy.service.session.SessionInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the SessionInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def update(self, unique_name=values.unset, ttl=values.unset, - status=values.unset, participants=values.unset): - """ - Update the SessionInstance - - :param unicode unique_name: A unique, developer assigned name of this Session. - :param unicode ttl: How long will this session stay open, in seconds. - :param SessionInstance.Status status: The Status of this Session - :param unicode participants: The participants - - :returns: Updated SessionInstance - :rtype: twilio.rest.preview.proxy.service.session.SessionInstance - """ - return self._proxy.update( - unique_name=unique_name, - ttl=ttl, - status=status, - participants=participants, - ) - - @property - def interactions(self): - """ - Access the interactions - - :returns: twilio.rest.preview.proxy.service.session.interaction.InteractionList - :rtype: twilio.rest.preview.proxy.service.session.interaction.InteractionList - """ - return self._proxy.interactions - - @property - def participants(self): - """ - Access the participants - - :returns: twilio.rest.preview.proxy.service.session.participant.ParticipantList - :rtype: twilio.rest.preview.proxy.service.session.participant.ParticipantList - """ - return self._proxy.participants - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/proxy/service/session/interaction.py b/twilio/rest/preview/proxy/service/session/interaction.py deleted file mode 100644 index 399082b282..0000000000 --- a/twilio/rest/preview/proxy/service/session/interaction.py +++ /dev/null @@ -1,537 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page - - -class InteractionList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid, session_sid): - """ - Initialize the InteractionList - - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param session_sid: Session Sid. - - :returns: twilio.rest.preview.proxy.service.session.interaction.InteractionList - :rtype: twilio.rest.preview.proxy.service.session.interaction.InteractionList - """ - super(InteractionList, self).__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, inbound_participant_status=values.unset, - outbound_participant_status=values.unset, limit=None, - page_size=None): - """ - 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 InteractionInstance.ResourceStatus inbound_participant_status: The Inbound Participant Status of this Interaction - :param InteractionInstance.ResourceStatus outbound_participant_status: The Outbound Participant Status of this Interaction - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.proxy.service.session.interaction.InteractionInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page( - inbound_participant_status=inbound_participant_status, - outbound_participant_status=outbound_participant_status, - page_size=limits['page_size'], - ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, inbound_participant_status=values.unset, - outbound_participant_status=values.unset, limit=None, page_size=None): - """ - 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 InteractionInstance.ResourceStatus inbound_participant_status: The Inbound Participant Status of this Interaction - :param InteractionInstance.ResourceStatus outbound_participant_status: The Outbound Participant Status of this Interaction - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.proxy.service.session.interaction.InteractionInstance] - """ - return list(self.stream( - inbound_participant_status=inbound_participant_status, - outbound_participant_status=outbound_participant_status, - limit=limit, - page_size=page_size, - )) - - def page(self, inbound_participant_status=values.unset, - outbound_participant_status=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of InteractionInstance records from the API. - Request is executed immediately - - :param InteractionInstance.ResourceStatus inbound_participant_status: The Inbound Participant Status of this Interaction - :param InteractionInstance.ResourceStatus outbound_participant_status: The Outbound Participant Status of this Interaction - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of InteractionInstance - :rtype: twilio.rest.preview.proxy.service.session.interaction.InteractionPage - """ - params = values.of({ - 'InboundParticipantStatus': inbound_participant_status, - 'OutboundParticipantStatus': outbound_participant_status, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return InteractionPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of InteractionInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of InteractionInstance - :rtype: twilio.rest.preview.proxy.service.session.interaction.InteractionPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return InteractionPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a InteractionContext - - :param sid: A string that uniquely identifies this Interaction. - - :returns: twilio.rest.preview.proxy.service.session.interaction.InteractionContext - :rtype: twilio.rest.preview.proxy.service.session.interaction.InteractionContext - """ - return InteractionContext( - self._version, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], - sid=sid, - ) - - def __call__(self, sid): - """ - Constructs a InteractionContext - - :param sid: A string that uniquely identifies this Interaction. - - :returns: twilio.rest.preview.proxy.service.session.interaction.InteractionContext - :rtype: twilio.rest.preview.proxy.service.session.interaction.InteractionContext - """ - return InteractionContext( - self._version, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], - sid=sid, - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class InteractionPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the InteractionPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Service Sid. - :param session_sid: Session Sid. - - :returns: twilio.rest.preview.proxy.service.session.interaction.InteractionPage - :rtype: twilio.rest.preview.proxy.service.session.interaction.InteractionPage - """ - super(InteractionPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of InteractionInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.proxy.service.session.interaction.InteractionInstance - :rtype: twilio.rest.preview.proxy.service.session.interaction.InteractionInstance - """ - return InteractionInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class InteractionContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid, session_sid, sid): - """ - Initialize the InteractionContext - - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param session_sid: Session Sid. - :param sid: A string that uniquely identifies this Interaction. - - :returns: twilio.rest.preview.proxy.service.session.interaction.InteractionContext - :rtype: twilio.rest.preview.proxy.service.session.interaction.InteractionContext - """ - super(InteractionContext, self).__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 fetch(self): - """ - Fetch a InteractionInstance - - :returns: Fetched InteractionInstance - :rtype: twilio.rest.preview.proxy.service.session.interaction.InteractionInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return InteractionInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], - sid=self._solution['sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class InteractionInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - class Status(object): - COMPLETED = "completed" - IN_PROGRESS = "in-progress" - FAILED = "failed" - - class ResourceStatus(object): - QUEUED = "queued" - SENDING = "sending" - SENT = "sent" - FAILED = "failed" - DELIVERED = "delivered" - UNDELIVERED = "undelivered" - - def __init__(self, version, payload, service_sid, session_sid, sid=None): - """ - Initialize the InteractionInstance - - :returns: twilio.rest.preview.proxy.service.session.interaction.InteractionInstance - :rtype: twilio.rest.preview.proxy.service.session.interaction.InteractionInstance - """ - super(InteractionInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'session_sid': payload['session_sid'], - 'service_sid': payload['service_sid'], - 'account_sid': payload['account_sid'], - 'data': payload['data'], - 'status': payload['status'], - 'inbound_participant_sid': payload['inbound_participant_sid'], - 'inbound_resource_sid': payload['inbound_resource_sid'], - 'inbound_resource_status': payload['inbound_resource_status'], - 'inbound_resource_type': payload['inbound_resource_type'], - 'inbound_resource_url': payload['inbound_resource_url'], - 'outbound_participant_sid': payload['outbound_participant_sid'], - 'outbound_resource_sid': payload['outbound_resource_sid'], - 'outbound_resource_status': payload['outbound_resource_status'], - 'outbound_resource_type': payload['outbound_resource_type'], - 'outbound_resource_url': payload['outbound_resource_url'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'session_sid': session_sid, - 'sid': sid or self._properties['sid'], - } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.proxy.service.session.interaction.InteractionContext - """ - 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 - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Interaction. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def session_sid(self): - """ - :returns: Session Sid. - :rtype: unicode - """ - return self._properties['session_sid'] - - @property - def service_sid(self): - """ - :returns: Service Sid. - :rtype: unicode - """ - return self._properties['service_sid'] - - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def data(self): - """ - :returns: What happened in this Interaction. - :rtype: unicode - """ - return self._properties['data'] - - @property - def status(self): - """ - :returns: The Status of this Interaction - :rtype: InteractionInstance.Status - """ - return self._properties['status'] - - @property - def inbound_participant_sid(self): - """ - :returns: The inbound_participant_sid - :rtype: unicode - """ - return self._properties['inbound_participant_sid'] - - @property - def inbound_resource_sid(self): - """ - :returns: The SID of the inbound resource. - :rtype: unicode - """ - return self._properties['inbound_resource_sid'] - - @property - def inbound_resource_status(self): - """ - :returns: The Inbound Resource Status of this Interaction - :rtype: InteractionInstance.ResourceStatus - """ - return self._properties['inbound_resource_status'] - - @property - def inbound_resource_type(self): - """ - :returns: The Twilio object type of the inbound resource. - :rtype: unicode - """ - return self._properties['inbound_resource_type'] - - @property - def inbound_resource_url(self): - """ - :returns: The URL of the inbound resource. - :rtype: unicode - """ - return self._properties['inbound_resource_url'] - - @property - def outbound_participant_sid(self): - """ - :returns: The outbound_participant_sid - :rtype: unicode - """ - return self._properties['outbound_participant_sid'] - - @property - def outbound_resource_sid(self): - """ - :returns: The SID of the outbound resource. - :rtype: unicode - """ - return self._properties['outbound_resource_sid'] - - @property - def outbound_resource_status(self): - """ - :returns: The Outbound Resource Status of this Interaction - :rtype: InteractionInstance.ResourceStatus - """ - return self._properties['outbound_resource_status'] - - @property - def outbound_resource_type(self): - """ - :returns: The Twilio object type of the outbound resource. - :rtype: unicode - """ - return self._properties['outbound_resource_type'] - - @property - def outbound_resource_url(self): - """ - :returns: The URL of the outbound resource. - :rtype: unicode - """ - return self._properties['outbound_resource_url'] - - @property - def date_created(self): - """ - :returns: The date this Interaction was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date this Interaction was updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def url(self): - """ - :returns: The URL of this Interaction. - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch a InteractionInstance - - :returns: Fetched InteractionInstance - :rtype: twilio.rest.preview.proxy.service.session.interaction.InteractionInstance - """ - return self._proxy.fetch() - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/proxy/service/session/participant/__init__.py b/twilio/rest/preview/proxy/service/session/participant/__init__.py deleted file mode 100644 index 2f7df4589f..0000000000 --- a/twilio/rest/preview/proxy/service/session/participant/__init__.py +++ /dev/null @@ -1,595 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page -from twilio.rest.preview.proxy.service.session.participant.message_interaction import MessageInteractionList - - -class ParticipantList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid, session_sid): - """ - Initialize the ParticipantList - - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param session_sid: Session Sid. - - :returns: twilio.rest.preview.proxy.service.session.participant.ParticipantList - :rtype: twilio.rest.preview.proxy.service.session.participant.ParticipantList - """ - super(ParticipantList, self).__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 stream(self, identifier=values.unset, participant_type=values.unset, - limit=None, page_size=None): - """ - 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 unicode identifier: The Participant's contact identifier, normally a phone number. - :param ParticipantInstance.ParticipantType participant_type: The Type of this Participant - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.proxy.service.session.participant.ParticipantInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page( - identifier=identifier, - participant_type=participant_type, - page_size=limits['page_size'], - ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, identifier=values.unset, participant_type=values.unset, - limit=None, page_size=None): - """ - 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 unicode identifier: The Participant's contact identifier, normally a phone number. - :param ParticipantInstance.ParticipantType participant_type: The Type of this Participant - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.proxy.service.session.participant.ParticipantInstance] - """ - return list(self.stream( - identifier=identifier, - participant_type=participant_type, - limit=limit, - page_size=page_size, - )) - - def page(self, identifier=values.unset, participant_type=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of ParticipantInstance records from the API. - Request is executed immediately - - :param unicode identifier: The Participant's contact identifier, normally a phone number. - :param ParticipantInstance.ParticipantType participant_type: The Type of this Participant - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of ParticipantInstance - :rtype: twilio.rest.preview.proxy.service.session.participant.ParticipantPage - """ - params = values.of({ - 'Identifier': identifier, - 'ParticipantType': participant_type, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return ParticipantPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of ParticipantInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of ParticipantInstance - :rtype: twilio.rest.preview.proxy.service.session.participant.ParticipantPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ParticipantPage(self._version, response, self._solution) - - def create(self, identifier, friendly_name=values.unset, - participant_type=values.unset): - """ - Create a new ParticipantInstance - - :param unicode identifier: The Participant's contact identifier, normally a phone number. - :param unicode friendly_name: A human readable description of this resource - :param ParticipantInstance.ParticipantType participant_type: The Type of this Participant - - :returns: Newly created ParticipantInstance - :rtype: twilio.rest.preview.proxy.service.session.participant.ParticipantInstance - """ - data = values.of({ - 'Identifier': identifier, - 'FriendlyName': friendly_name, - 'ParticipantType': participant_type, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return ParticipantInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], - ) - - def get(self, sid): - """ - Constructs a ParticipantContext - - :param sid: A string that uniquely identifies this Participant. - - :returns: twilio.rest.preview.proxy.service.session.participant.ParticipantContext - :rtype: twilio.rest.preview.proxy.service.session.participant.ParticipantContext - """ - return ParticipantContext( - self._version, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], - sid=sid, - ) - - def __call__(self, sid): - """ - Constructs a ParticipantContext - - :param sid: A string that uniquely identifies this Participant. - - :returns: twilio.rest.preview.proxy.service.session.participant.ParticipantContext - :rtype: twilio.rest.preview.proxy.service.session.participant.ParticipantContext - """ - return ParticipantContext( - self._version, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], - sid=sid, - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ParticipantPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the ParticipantPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Service Sid. - :param session_sid: Session Sid. - - :returns: twilio.rest.preview.proxy.service.session.participant.ParticipantPage - :rtype: twilio.rest.preview.proxy.service.session.participant.ParticipantPage - """ - super(ParticipantPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of ParticipantInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.proxy.service.session.participant.ParticipantInstance - :rtype: twilio.rest.preview.proxy.service.session.participant.ParticipantInstance - """ - return ParticipantInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ParticipantContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid, session_sid, sid): - """ - Initialize the ParticipantContext - - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param session_sid: Session Sid. - :param sid: A string that uniquely identifies this Participant. - - :returns: twilio.rest.preview.proxy.service.session.participant.ParticipantContext - :rtype: twilio.rest.preview.proxy.service.session.participant.ParticipantContext - """ - super(ParticipantContext, self).__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) - - # Dependents - self._message_interactions = None - - def fetch(self): - """ - Fetch a ParticipantInstance - - :returns: Fetched ParticipantInstance - :rtype: twilio.rest.preview.proxy.service.session.participant.ParticipantInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return ParticipantInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the ParticipantInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def update(self, participant_type=values.unset, identifier=values.unset, - friendly_name=values.unset): - """ - Update the ParticipantInstance - - :param ParticipantInstance.ParticipantType participant_type: The Type of this Participant - :param unicode identifier: The Participant's contact identifier, normally a phone number. - :param unicode friendly_name: A human readable description of this resource - - :returns: Updated ParticipantInstance - :rtype: twilio.rest.preview.proxy.service.session.participant.ParticipantInstance - """ - data = values.of({ - 'ParticipantType': participant_type, - 'Identifier': identifier, - 'FriendlyName': friendly_name, - }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - 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): - """ - Access the message_interactions - - :returns: twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionList - :rtype: twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionList - """ - if self._message_interactions is None: - self._message_interactions = MessageInteractionList( - self._version, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], - participant_sid=self._solution['sid'], - ) - return self._message_interactions - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class ParticipantInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - class ParticipantType(object): - SMS = "sms" - VOICE = "voice" - PHONE = "phone" - - def __init__(self, version, payload, service_sid, session_sid, sid=None): - """ - Initialize the ParticipantInstance - - :returns: twilio.rest.preview.proxy.service.session.participant.ParticipantInstance - :rtype: twilio.rest.preview.proxy.service.session.participant.ParticipantInstance - """ - super(ParticipantInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'session_sid': payload['session_sid'], - 'service_sid': payload['service_sid'], - 'account_sid': payload['account_sid'], - 'friendly_name': payload['friendly_name'], - 'participant_type': payload['participant_type'], - 'identifier': payload['identifier'], - 'proxy_identifier': payload['proxy_identifier'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - 'links': payload['links'], - } - - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'session_sid': session_sid, - 'sid': sid or self._properties['sid'], - } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.proxy.service.session.participant.ParticipantContext - """ - 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 - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Participant. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def session_sid(self): - """ - :returns: Session Sid. - :rtype: unicode - """ - return self._properties['session_sid'] - - @property - def service_sid(self): - """ - :returns: Service Sid. - :rtype: unicode - """ - return self._properties['service_sid'] - - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def friendly_name(self): - """ - :returns: A human readable description of this resource - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def participant_type(self): - """ - :returns: The Type of this Participant - :rtype: ParticipantInstance.ParticipantType - """ - return self._properties['participant_type'] - - @property - def identifier(self): - """ - :returns: The Participant's contact identifier, normally a phone number. - :rtype: unicode - """ - return self._properties['identifier'] - - @property - def proxy_identifier(self): - """ - :returns: What this Participant communicates with, normally a phone number. - :rtype: unicode - """ - return self._properties['proxy_identifier'] - - @property - def date_created(self): - """ - :returns: The date this Participant was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date this Participant was updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def url(self): - """ - :returns: The URL of this resource. - :rtype: unicode - """ - return self._properties['url'] - - @property - def links(self): - """ - :returns: Nested resource URLs. - :rtype: unicode - """ - return self._properties['links'] - - def fetch(self): - """ - Fetch a ParticipantInstance - - :returns: Fetched ParticipantInstance - :rtype: twilio.rest.preview.proxy.service.session.participant.ParticipantInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the ParticipantInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def update(self, participant_type=values.unset, identifier=values.unset, - friendly_name=values.unset): - """ - Update the ParticipantInstance - - :param ParticipantInstance.ParticipantType participant_type: The Type of this Participant - :param unicode identifier: The Participant's contact identifier, normally a phone number. - :param unicode friendly_name: A human readable description of this resource - - :returns: Updated ParticipantInstance - :rtype: twilio.rest.preview.proxy.service.session.participant.ParticipantInstance - """ - return self._proxy.update( - participant_type=participant_type, - identifier=identifier, - friendly_name=friendly_name, - ) - - @property - def message_interactions(self): - """ - Access the message_interactions - - :returns: twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionList - :rtype: twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionList - """ - return self._proxy.message_interactions - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/proxy/service/session/participant/message_interaction.py b/twilio/rest/preview/proxy/service/session/participant/message_interaction.py deleted file mode 100644 index 8e063e4f75..0000000000 --- a/twilio/rest/preview/proxy/service/session/participant/message_interaction.py +++ /dev/null @@ -1,567 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import serialize -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.page import Page - - -class MessageInteractionList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid, session_sid, participant_sid): - """ - Initialize the MessageInteractionList - - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param session_sid: Session Sid. - :param participant_sid: The participant_sid - - :returns: twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionList - :rtype: twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionList - """ - super(MessageInteractionList, self).__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=values.unset, media_url=values.unset): - """ - Create a new MessageInteractionInstance - - :param unicode body: The body of the message. Up to 1600 characters long. - :param unicode media_url: The url of an image or video. - - :returns: Newly created MessageInteractionInstance - :rtype: twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionInstance - """ - data = values.of({'Body': body, 'MediaUrl': serialize.map(media_url, lambda e: e), }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - 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=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of MessageInteractionInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of MessageInteractionInstance - :rtype: twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionPage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return MessageInteractionPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of MessageInteractionInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of MessageInteractionInstance - :rtype: twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return MessageInteractionPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a MessageInteractionContext - - :param sid: A string that uniquely identifies this Interaction. - - :returns: twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionContext - :rtype: twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionContext - """ - 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): - """ - Constructs a MessageInteractionContext - - :param sid: A string that uniquely identifies this Interaction. - - :returns: twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionContext - :rtype: twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionContext - """ - 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): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class MessageInteractionPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the MessageInteractionPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Service Sid. - :param session_sid: Session Sid. - :param participant_sid: The participant_sid - - :returns: twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionPage - :rtype: twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionPage - """ - super(MessageInteractionPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of MessageInteractionInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionInstance - :rtype: twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionInstance - """ - 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): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class MessageInteractionContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid, session_sid, participant_sid, sid): - """ - Initialize the MessageInteractionContext - - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param session_sid: Session Sid. - :param participant_sid: Participant Sid. - :param sid: A string that uniquely identifies this Interaction. - - :returns: twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionContext - :rtype: twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionContext - """ - super(MessageInteractionContext, self).__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): - """ - Fetch a MessageInteractionInstance - - :returns: Fetched MessageInteractionInstance - :rtype: twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - 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): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class MessageInteractionInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - class Status(object): - COMPLETED = "completed" - IN_PROGRESS = "in-progress" - FAILED = "failed" - - class ResourceStatus(object): - QUEUED = "queued" - SENDING = "sending" - SENT = "sent" - FAILED = "failed" - DELIVERED = "delivered" - UNDELIVERED = "undelivered" - - def __init__(self, version, payload, service_sid, session_sid, participant_sid, - sid=None): - """ - Initialize the MessageInteractionInstance - - :returns: twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionInstance - :rtype: twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionInstance - """ - super(MessageInteractionInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'session_sid': payload['session_sid'], - 'service_sid': payload['service_sid'], - 'account_sid': payload['account_sid'], - 'data': payload['data'], - 'status': payload['status'], - 'participant_sid': payload['participant_sid'], - 'inbound_participant_sid': payload['inbound_participant_sid'], - 'inbound_resource_sid': payload['inbound_resource_sid'], - 'inbound_resource_status': payload['inbound_resource_status'], - 'inbound_resource_type': payload['inbound_resource_type'], - 'inbound_resource_url': payload['inbound_resource_url'], - 'outbound_participant_sid': payload['outbound_participant_sid'], - 'outbound_resource_sid': payload['outbound_resource_sid'], - 'outbound_resource_status': payload['outbound_resource_status'], - 'outbound_resource_type': payload['outbound_resource_type'], - 'outbound_resource_url': payload['outbound_resource_url'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'session_sid': session_sid, - 'participant_sid': participant_sid, - 'sid': sid or self._properties['sid'], - } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionContext - """ - 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 - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Interaction. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def session_sid(self): - """ - :returns: Session Sid. - :rtype: unicode - """ - return self._properties['session_sid'] - - @property - def service_sid(self): - """ - :returns: Service Sid. - :rtype: unicode - """ - return self._properties['service_sid'] - - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def data(self): - """ - :returns: What happened in this Interaction. - :rtype: unicode - """ - return self._properties['data'] - - @property - def status(self): - """ - :returns: The Status of this Interaction - :rtype: MessageInteractionInstance.Status - """ - return self._properties['status'] - - @property - def participant_sid(self): - """ - :returns: The participant_sid - :rtype: unicode - """ - return self._properties['participant_sid'] - - @property - def inbound_participant_sid(self): - """ - :returns: The inbound_participant_sid - :rtype: unicode - """ - return self._properties['inbound_participant_sid'] - - @property - def inbound_resource_sid(self): - """ - :returns: The SID of the inbound resource. - :rtype: unicode - """ - return self._properties['inbound_resource_sid'] - - @property - def inbound_resource_status(self): - """ - :returns: The Inbound Resource Status of this Interaction - :rtype: MessageInteractionInstance.ResourceStatus - """ - return self._properties['inbound_resource_status'] - - @property - def inbound_resource_type(self): - """ - :returns: The Twilio object type of the inbound resource. - :rtype: unicode - """ - return self._properties['inbound_resource_type'] - - @property - def inbound_resource_url(self): - """ - :returns: The URL of the inbound resource. - :rtype: unicode - """ - return self._properties['inbound_resource_url'] - - @property - def outbound_participant_sid(self): - """ - :returns: The outbound_participant_sid - :rtype: unicode - """ - return self._properties['outbound_participant_sid'] - - @property - def outbound_resource_sid(self): - """ - :returns: The SID of the outbound resource. - :rtype: unicode - """ - return self._properties['outbound_resource_sid'] - - @property - def outbound_resource_status(self): - """ - :returns: The Outbound Resource Status of this Interaction - :rtype: MessageInteractionInstance.ResourceStatus - """ - return self._properties['outbound_resource_status'] - - @property - def outbound_resource_type(self): - """ - :returns: The Twilio object type of the outbound resource. - :rtype: unicode - """ - return self._properties['outbound_resource_type'] - - @property - def outbound_resource_url(self): - """ - :returns: The URL of the outbound resource. - :rtype: unicode - """ - return self._properties['outbound_resource_url'] - - @property - def date_created(self): - """ - :returns: The date this Interaction was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date this Interaction was updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def url(self): - """ - :returns: The URL of this Interaction. - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch a MessageInteractionInstance - - :returns: Fetched MessageInteractionInstance - :rtype: twilio.rest.preview.proxy.service.session.participant.message_interaction.MessageInteractionInstance - """ - return self._proxy.fetch() - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/proxy/service/short_code.py b/twilio/rest/preview/proxy/service/short_code.py deleted file mode 100644 index a0488a0c61..0000000000 --- a/twilio/rest/preview/proxy/service/short_code.py +++ /dev/null @@ -1,422 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page - - -class ShortCodeList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid): - """ - Initialize the ShortCodeList - - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - - :returns: twilio.rest.preview.proxy.service.short_code.ShortCodeList - :rtype: twilio.rest.preview.proxy.service.short_code.ShortCodeList - """ - super(ShortCodeList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/ShortCodes'.format(**self._solution) - - def create(self, sid): - """ - Create a new ShortCodeInstance - - :param unicode sid: Delete by unique shortcode Sid - - :returns: Newly created ShortCodeInstance - :rtype: twilio.rest.preview.proxy.service.short_code.ShortCodeInstance - """ - data = values.of({'Sid': sid, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return ShortCodeInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def stream(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.proxy.service.short_code.ShortCodeInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.proxy.service.short_code.ShortCodeInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of ShortCodeInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of ShortCodeInstance - :rtype: twilio.rest.preview.proxy.service.short_code.ShortCodePage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return ShortCodePage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of ShortCodeInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of ShortCodeInstance - :rtype: twilio.rest.preview.proxy.service.short_code.ShortCodePage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ShortCodePage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a ShortCodeContext - - :param sid: Fetch by unique shortcode Sid - - :returns: twilio.rest.preview.proxy.service.short_code.ShortCodeContext - :rtype: twilio.rest.preview.proxy.service.short_code.ShortCodeContext - """ - return ShortCodeContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a ShortCodeContext - - :param sid: Fetch by unique shortcode Sid - - :returns: twilio.rest.preview.proxy.service.short_code.ShortCodeContext - :rtype: twilio.rest.preview.proxy.service.short_code.ShortCodeContext - """ - return ShortCodeContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ShortCodePage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the ShortCodePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Service Sid. - - :returns: twilio.rest.preview.proxy.service.short_code.ShortCodePage - :rtype: twilio.rest.preview.proxy.service.short_code.ShortCodePage - """ - super(ShortCodePage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of ShortCodeInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.proxy.service.short_code.ShortCodeInstance - :rtype: twilio.rest.preview.proxy.service.short_code.ShortCodeInstance - """ - return ShortCodeInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ShortCodeContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid, sid): - """ - Initialize the ShortCodeContext - - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: Fetch by unique shortcode Sid - - :returns: twilio.rest.preview.proxy.service.short_code.ShortCodeContext - :rtype: twilio.rest.preview.proxy.service.short_code.ShortCodeContext - """ - super(ShortCodeContext, self).__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): - """ - Deletes the ShortCodeInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def fetch(self): - """ - Fetch a ShortCodeInstance - - :returns: Fetched ShortCodeInstance - :rtype: twilio.rest.preview.proxy.service.short_code.ShortCodeInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return ShortCodeInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class ShortCodeInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the ShortCodeInstance - - :returns: twilio.rest.preview.proxy.service.short_code.ShortCodeInstance - :rtype: twilio.rest.preview.proxy.service.short_code.ShortCodeInstance - """ - super(ShortCodeInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'short_code': payload['short_code'], - 'country_code': payload['country_code'], - 'capabilities': payload['capabilities'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.proxy.service.short_code.ShortCodeContext - """ - if self._context is None: - self._context = ShortCodeContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this resource - :rtype: unicode - """ - return self._properties['sid'] - - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def service_sid(self): - """ - :returns: Service Sid. - :rtype: unicode - """ - return self._properties['service_sid'] - - @property - def date_created(self): - """ - :returns: The date this resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date this resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def short_code(self): - """ - :returns: The short code. e.g., 894546. - :rtype: unicode - """ - return self._properties['short_code'] - - @property - def country_code(self): - """ - :returns: The ISO 3166-1 alpha-2 country code - :rtype: unicode - """ - return self._properties['country_code'] - - @property - def capabilities(self): - """ - :returns: Indicate if a shortcode can receive messages - :rtype: dict - """ - return self._properties['capabilities'] - - @property - def url(self): - """ - :returns: The URL of this resource. - :rtype: unicode - """ - return self._properties['url'] - - def delete(self): - """ - Deletes the ShortCodeInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def fetch(self): - """ - Fetch a ShortCodeInstance - - :returns: Fetched ShortCodeInstance - :rtype: twilio.rest.preview.proxy.service.short_code.ShortCodeInstance - """ - return self._proxy.fetch() - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/studio/__init__.py b/twilio/rest/preview/studio/__init__.py deleted file mode 100644 index 1c4898cb24..0000000000 --- a/twilio/rest/preview/studio/__init__.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base.version import Version -from twilio.rest.preview.studio.flow import FlowList - - -class Studio(Version): - - def __init__(self, domain): - """ - Initialize the Studio version of Preview - - :returns: Studio version of Preview - :rtype: twilio.rest.preview.studio.Studio.Studio - """ - super(Studio, self).__init__(domain) - self.version = 'Studio' - self._flows = None - - @property - def flows(self): - """ - :rtype: twilio.rest.preview.studio.flow.FlowList - """ - if self._flows is None: - self._flows = FlowList(self) - return self._flows - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/preview/studio/flow/__init__.py b/twilio/rest/preview/studio/flow/__init__.py deleted file mode 100644 index b5640328c3..0000000000 --- a/twilio/rest/preview/studio/flow/__init__.py +++ /dev/null @@ -1,430 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page -from twilio.rest.preview.studio.flow.engagement import EngagementList - - -class FlowList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version): - """ - Initialize the FlowList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.preview.studio.flow.FlowList - :rtype: twilio.rest.preview.studio.flow.FlowList - """ - super(FlowList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Flows'.format(**self._solution) - - def stream(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.studio.flow.FlowInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.studio.flow.FlowInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of FlowInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of FlowInstance - :rtype: twilio.rest.preview.studio.flow.FlowPage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return FlowPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of FlowInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of FlowInstance - :rtype: twilio.rest.preview.studio.flow.FlowPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return FlowPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a FlowContext - - :param sid: The sid - - :returns: twilio.rest.preview.studio.flow.FlowContext - :rtype: twilio.rest.preview.studio.flow.FlowContext - """ - return FlowContext(self._version, sid=sid, ) - - def __call__(self, sid): - """ - Constructs a FlowContext - - :param sid: The sid - - :returns: twilio.rest.preview.studio.flow.FlowContext - :rtype: twilio.rest.preview.studio.flow.FlowContext - """ - return FlowContext(self._version, sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class FlowPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the FlowPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.preview.studio.flow.FlowPage - :rtype: twilio.rest.preview.studio.flow.FlowPage - """ - super(FlowPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of FlowInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.studio.flow.FlowInstance - :rtype: twilio.rest.preview.studio.flow.FlowInstance - """ - return FlowInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class FlowContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, sid): - """ - Initialize the FlowContext - - :param Version version: Version that contains the resource - :param sid: The sid - - :returns: twilio.rest.preview.studio.flow.FlowContext - :rtype: twilio.rest.preview.studio.flow.FlowContext - """ - super(FlowContext, self).__init__(version) - - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Flows/{sid}'.format(**self._solution) - - # Dependents - self._engagements = None - - def fetch(self): - """ - Fetch a FlowInstance - - :returns: Fetched FlowInstance - :rtype: twilio.rest.preview.studio.flow.FlowInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return FlowInstance(self._version, payload, sid=self._solution['sid'], ) - - def delete(self): - """ - Deletes the FlowInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - @property - def engagements(self): - """ - Access the engagements - - :returns: twilio.rest.preview.studio.flow.engagement.EngagementList - :rtype: twilio.rest.preview.studio.flow.engagement.EngagementList - """ - if self._engagements is None: - self._engagements = EngagementList(self._version, flow_sid=self._solution['sid'], ) - return self._engagements - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class FlowInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - class Status(object): - DRAFT = "draft" - PUBLISHED = "published" - - def __init__(self, version, payload, sid=None): - """ - Initialize the FlowInstance - - :returns: twilio.rest.preview.studio.flow.FlowInstance - :rtype: twilio.rest.preview.studio.flow.FlowInstance - """ - super(FlowInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'friendly_name': payload['friendly_name'], - 'status': payload['status'], - 'debug': payload['debug'], - 'version': deserialize.integer(payload['version']), - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - 'links': payload['links'], - } - - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.studio.flow.FlowContext - """ - if self._context is None: - self._context = FlowContext(self._version, sid=self._solution['sid'], ) - return self._context - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Flow. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def friendly_name(self): - """ - :returns: A human readable description of this resource. - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def status(self): - """ - :returns: The Status of this Flow - :rtype: FlowInstance.Status - """ - return self._properties['status'] - - @property - def debug(self): - """ - :returns: Toggle extra logging. - :rtype: bool - """ - return self._properties['debug'] - - @property - def version(self): - """ - :returns: The latest version number of this Flow's definition. - :rtype: unicode - """ - return self._properties['version'] - - @property - def date_created(self): - """ - :returns: The date this Flow was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date this Flow was updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def url(self): - """ - :returns: The URL of this resource. - :rtype: unicode - """ - return self._properties['url'] - - @property - def links(self): - """ - :returns: Nested resource URLs. - :rtype: unicode - """ - return self._properties['links'] - - def fetch(self): - """ - Fetch a FlowInstance - - :returns: Fetched FlowInstance - :rtype: twilio.rest.preview.studio.flow.FlowInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the FlowInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - @property - def engagements(self): - """ - Access the engagements - - :returns: twilio.rest.preview.studio.flow.engagement.EngagementList - :rtype: twilio.rest.preview.studio.flow.engagement.EngagementList - """ - return self._proxy.engagements - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/studio/flow/engagement/__init__.py b/twilio/rest/preview/studio/flow/engagement/__init__.py deleted file mode 100644 index be08319e05..0000000000 --- a/twilio/rest/preview/studio/flow/engagement/__init__.py +++ /dev/null @@ -1,458 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page -from twilio.rest.preview.studio.flow.engagement.step import StepList - - -class EngagementList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, flow_sid): - """ - Initialize the EngagementList - - :param Version version: Version that contains the resource - :param flow_sid: Flow Sid. - - :returns: twilio.rest.preview.studio.flow.engagement.EngagementList - :rtype: twilio.rest.preview.studio.flow.engagement.EngagementList - """ - super(EngagementList, self).__init__(version) - - # Path Solution - self._solution = {'flow_sid': flow_sid, } - self._uri = '/Flows/{flow_sid}/Engagements'.format(**self._solution) - - def stream(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.studio.flow.engagement.EngagementInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.studio.flow.engagement.EngagementInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of EngagementInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of EngagementInstance - :rtype: twilio.rest.preview.studio.flow.engagement.EngagementPage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return EngagementPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of EngagementInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of EngagementInstance - :rtype: twilio.rest.preview.studio.flow.engagement.EngagementPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return EngagementPage(self._version, response, self._solution) - - def create(self, to, from_, parameters=values.unset): - """ - Create a new EngagementInstance - - :param unicode to: The to - :param unicode from_: The from - :param unicode parameters: The parameters - - :returns: Newly created EngagementInstance - :rtype: twilio.rest.preview.studio.flow.engagement.EngagementInstance - """ - data = values.of({'To': to, 'From': from_, 'Parameters': parameters, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return EngagementInstance(self._version, payload, flow_sid=self._solution['flow_sid'], ) - - def get(self, sid): - """ - Constructs a EngagementContext - - :param sid: The sid - - :returns: twilio.rest.preview.studio.flow.engagement.EngagementContext - :rtype: twilio.rest.preview.studio.flow.engagement.EngagementContext - """ - return EngagementContext(self._version, flow_sid=self._solution['flow_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a EngagementContext - - :param sid: The sid - - :returns: twilio.rest.preview.studio.flow.engagement.EngagementContext - :rtype: twilio.rest.preview.studio.flow.engagement.EngagementContext - """ - return EngagementContext(self._version, flow_sid=self._solution['flow_sid'], sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class EngagementPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the EngagementPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param flow_sid: Flow Sid. - - :returns: twilio.rest.preview.studio.flow.engagement.EngagementPage - :rtype: twilio.rest.preview.studio.flow.engagement.EngagementPage - """ - super(EngagementPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of EngagementInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.studio.flow.engagement.EngagementInstance - :rtype: twilio.rest.preview.studio.flow.engagement.EngagementInstance - """ - return EngagementInstance(self._version, payload, flow_sid=self._solution['flow_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class EngagementContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, flow_sid, sid): - """ - Initialize the EngagementContext - - :param Version version: Version that contains the resource - :param flow_sid: The flow_sid - :param sid: The sid - - :returns: twilio.rest.preview.studio.flow.engagement.EngagementContext - :rtype: twilio.rest.preview.studio.flow.engagement.EngagementContext - """ - super(EngagementContext, self).__init__(version) - - # Path Solution - self._solution = {'flow_sid': flow_sid, 'sid': sid, } - self._uri = '/Flows/{flow_sid}/Engagements/{sid}'.format(**self._solution) - - # Dependents - self._steps = None - - def fetch(self): - """ - Fetch a EngagementInstance - - :returns: Fetched EngagementInstance - :rtype: twilio.rest.preview.studio.flow.engagement.EngagementInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return EngagementInstance( - self._version, - payload, - flow_sid=self._solution['flow_sid'], - sid=self._solution['sid'], - ) - - @property - def steps(self): - """ - Access the steps - - :returns: twilio.rest.preview.studio.flow.engagement.step.StepList - :rtype: twilio.rest.preview.studio.flow.engagement.step.StepList - """ - if self._steps is None: - self._steps = StepList( - self._version, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['sid'], - ) - return self._steps - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class EngagementInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - class Status(object): - ACTIVE = "active" - ENDED = "ended" - - def __init__(self, version, payload, flow_sid, sid=None): - """ - Initialize the EngagementInstance - - :returns: twilio.rest.preview.studio.flow.engagement.EngagementInstance - :rtype: twilio.rest.preview.studio.flow.engagement.EngagementInstance - """ - super(EngagementInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'flow_sid': payload['flow_sid'], - 'contact_sid': payload['contact_sid'], - 'contact_channel_address': payload['contact_channel_address'], - 'status': payload['status'], - 'context': payload['context'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - 'links': payload['links'], - } - - # Context - self._context = None - self._solution = {'flow_sid': flow_sid, 'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.studio.flow.engagement.EngagementContext - """ - if self._context is None: - self._context = EngagementContext( - self._version, - flow_sid=self._solution['flow_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Engagement. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def flow_sid(self): - """ - :returns: Flow Sid. - :rtype: unicode - """ - return self._properties['flow_sid'] - - @property - def contact_sid(self): - """ - :returns: Contact Sid. - :rtype: unicode - """ - return self._properties['contact_sid'] - - @property - def contact_channel_address(self): - """ - :returns: The phone number, SIP address or Client identifier that triggered this Engagement. - :rtype: unicode - """ - return self._properties['contact_channel_address'] - - @property - def status(self): - """ - :returns: The Status of this Engagement - :rtype: EngagementInstance.Status - """ - return self._properties['status'] - - @property - def context(self): - """ - :returns: Nested resource URLs. - :rtype: dict - """ - return self._properties['context'] - - @property - def date_created(self): - """ - :returns: The date this Engagement was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date this Engagement was updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def url(self): - """ - :returns: The URL of this resource. - :rtype: unicode - """ - return self._properties['url'] - - @property - def links(self): - """ - :returns: Nested resource URLs. - :rtype: unicode - """ - return self._properties['links'] - - def fetch(self): - """ - Fetch a EngagementInstance - - :returns: Fetched EngagementInstance - :rtype: twilio.rest.preview.studio.flow.engagement.EngagementInstance - """ - return self._proxy.fetch() - - @property - def steps(self): - """ - Access the steps - - :returns: twilio.rest.preview.studio.flow.engagement.step.StepList - :rtype: twilio.rest.preview.studio.flow.engagement.step.StepList - """ - return self._proxy.steps - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/studio/flow/engagement/step.py b/twilio/rest/preview/studio/flow/engagement/step.py deleted file mode 100644 index b0a67753ed..0000000000 --- a/twilio/rest/preview/studio/flow/engagement/step.py +++ /dev/null @@ -1,427 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page - - -class StepList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, flow_sid, engagement_sid): - """ - Initialize the StepList - - :param Version version: Version that contains the resource - :param flow_sid: Flow Sid. - :param engagement_sid: Engagement Sid. - - :returns: twilio.rest.preview.studio.flow.engagement.step.StepList - :rtype: twilio.rest.preview.studio.flow.engagement.step.StepList - """ - super(StepList, self).__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=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.studio.flow.engagement.step.StepInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.studio.flow.engagement.step.StepInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of StepInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of StepInstance - :rtype: twilio.rest.preview.studio.flow.engagement.step.StepPage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return StepPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of StepInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of StepInstance - :rtype: twilio.rest.preview.studio.flow.engagement.step.StepPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return StepPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a StepContext - - :param sid: The sid - - :returns: twilio.rest.preview.studio.flow.engagement.step.StepContext - :rtype: twilio.rest.preview.studio.flow.engagement.step.StepContext - """ - return StepContext( - self._version, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['engagement_sid'], - sid=sid, - ) - - def __call__(self, sid): - """ - Constructs a StepContext - - :param sid: The sid - - :returns: twilio.rest.preview.studio.flow.engagement.step.StepContext - :rtype: twilio.rest.preview.studio.flow.engagement.step.StepContext - """ - return StepContext( - self._version, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['engagement_sid'], - sid=sid, - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class StepPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the StepPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param flow_sid: Flow Sid. - :param engagement_sid: Engagement Sid. - - :returns: twilio.rest.preview.studio.flow.engagement.step.StepPage - :rtype: twilio.rest.preview.studio.flow.engagement.step.StepPage - """ - super(StepPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of StepInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.studio.flow.engagement.step.StepInstance - :rtype: twilio.rest.preview.studio.flow.engagement.step.StepInstance - """ - return StepInstance( - self._version, - payload, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['engagement_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class StepContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, flow_sid, engagement_sid, sid): - """ - Initialize the StepContext - - :param Version version: Version that contains the resource - :param flow_sid: The flow_sid - :param engagement_sid: The engagement_sid - :param sid: The sid - - :returns: twilio.rest.preview.studio.flow.engagement.step.StepContext - :rtype: twilio.rest.preview.studio.flow.engagement.step.StepContext - """ - super(StepContext, self).__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) - - def fetch(self): - """ - Fetch a StepInstance - - :returns: Fetched StepInstance - :rtype: twilio.rest.preview.studio.flow.engagement.step.StepInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return StepInstance( - self._version, - payload, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['engagement_sid'], - sid=self._solution['sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class StepInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, flow_sid, engagement_sid, sid=None): - """ - Initialize the StepInstance - - :returns: twilio.rest.preview.studio.flow.engagement.step.StepInstance - :rtype: twilio.rest.preview.studio.flow.engagement.step.StepInstance - """ - super(StepInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'flow_sid': payload['flow_sid'], - 'engagement_sid': payload['engagement_sid'], - 'name': payload['name'], - 'context': payload['context'], - 'transitioned_from': payload['transitioned_from'], - 'transitioned_to': payload['transitioned_to'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = { - 'flow_sid': flow_sid, - 'engagement_sid': engagement_sid, - 'sid': sid or self._properties['sid'], - } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.studio.flow.engagement.step.StepContext - """ - 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 - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Step. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def flow_sid(self): - """ - :returns: Flow Sid. - :rtype: unicode - """ - return self._properties['flow_sid'] - - @property - def engagement_sid(self): - """ - :returns: Engagement Sid. - :rtype: unicode - """ - return self._properties['engagement_sid'] - - @property - def name(self): - """ - :returns: The Widget that implemented this Step. - :rtype: unicode - """ - return self._properties['name'] - - @property - def context(self): - """ - :returns: Nested resource URLs. - :rtype: dict - """ - return self._properties['context'] - - @property - def transitioned_from(self): - """ - :returns: The Widget that preceded the Widget for this Step. - :rtype: unicode - """ - return self._properties['transitioned_from'] - - @property - def transitioned_to(self): - """ - :returns: The Widget that will follow the Widget for this Step. - :rtype: unicode - """ - return self._properties['transitioned_to'] - - @property - def date_created(self): - """ - :returns: The date this Step was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date this Step was updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def url(self): - """ - :returns: The URL of this resource. - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch a StepInstance - - :returns: Fetched StepInstance - :rtype: twilio.rest.preview.studio.flow.engagement.step.StepInstance - """ - return self._proxy.fetch() - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/sync/__init__.py b/twilio/rest/preview/sync/__init__.py deleted file mode 100644 index 38f1fafb37..0000000000 --- a/twilio/rest/preview/sync/__init__.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base.version import Version -from twilio.rest.preview.sync.service import ServiceList - - -class Sync(Version): - - def __init__(self, domain): - """ - Initialize the Sync version of Preview - - :returns: Sync version of Preview - :rtype: twilio.rest.preview.sync.Sync.Sync - """ - super(Sync, self).__init__(domain) - self.version = 'Sync' - self._services = None - - @property - def services(self): - """ - :rtype: twilio.rest.preview.sync.service.ServiceList - """ - if self._services is None: - self._services = ServiceList(self) - return self._services - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/preview/sync/service/__init__.py b/twilio/rest/preview/sync/service/__init__.py deleted file mode 100644 index 9eb166edf3..0000000000 --- a/twilio/rest/preview/sync/service/__init__.py +++ /dev/null @@ -1,553 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page -from twilio.rest.preview.sync.service.document import DocumentList -from twilio.rest.preview.sync.service.sync_list import SyncListList -from twilio.rest.preview.sync.service.sync_map import SyncMapList - - -class ServiceList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version): - """ - Initialize the ServiceList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.preview.sync.service.ServiceList - :rtype: twilio.rest.preview.sync.service.ServiceList - """ - super(ServiceList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Services'.format(**self._solution) - - def create(self, friendly_name=values.unset, webhook_url=values.unset, - reachability_webhooks_enabled=values.unset, - acl_enabled=values.unset): - """ - Create a new ServiceInstance - - :param unicode friendly_name: The friendly_name - :param unicode webhook_url: The webhook_url - :param bool reachability_webhooks_enabled: The reachability_webhooks_enabled - :param bool acl_enabled: The acl_enabled - - :returns: Newly created ServiceInstance - :rtype: twilio.rest.preview.sync.service.ServiceInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'WebhookUrl': webhook_url, - 'ReachabilityWebhooksEnabled': reachability_webhooks_enabled, - 'AclEnabled': acl_enabled, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return ServiceInstance(self._version, payload, ) - - def stream(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.ServiceInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.ServiceInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of ServiceInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of ServiceInstance - :rtype: twilio.rest.preview.sync.service.ServicePage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return ServicePage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of ServiceInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of ServiceInstance - :rtype: twilio.rest.preview.sync.service.ServicePage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ServicePage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a ServiceContext - - :param sid: The sid - - :returns: twilio.rest.preview.sync.service.ServiceContext - :rtype: twilio.rest.preview.sync.service.ServiceContext - """ - return ServiceContext(self._version, sid=sid, ) - - def __call__(self, sid): - """ - Constructs a ServiceContext - - :param sid: The sid - - :returns: twilio.rest.preview.sync.service.ServiceContext - :rtype: twilio.rest.preview.sync.service.ServiceContext - """ - return ServiceContext(self._version, sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ServicePage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the ServicePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.preview.sync.service.ServicePage - :rtype: twilio.rest.preview.sync.service.ServicePage - """ - super(ServicePage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of ServiceInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.sync.service.ServiceInstance - :rtype: twilio.rest.preview.sync.service.ServiceInstance - """ - return ServiceInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ServiceContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, sid): - """ - Initialize the ServiceContext - - :param Version version: Version that contains the resource - :param sid: The sid - - :returns: twilio.rest.preview.sync.service.ServiceContext - :rtype: twilio.rest.preview.sync.service.ServiceContext - """ - super(ServiceContext, self).__init__(version) - - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Services/{sid}'.format(**self._solution) - - # Dependents - self._documents = None - self._sync_lists = None - self._sync_maps = None - - def fetch(self): - """ - Fetch a ServiceInstance - - :returns: Fetched ServiceInstance - :rtype: twilio.rest.preview.sync.service.ServiceInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) - - def delete(self): - """ - Deletes the ServiceInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def update(self, webhook_url=values.unset, friendly_name=values.unset, - reachability_webhooks_enabled=values.unset, - acl_enabled=values.unset): - """ - Update the ServiceInstance - - :param unicode webhook_url: The webhook_url - :param unicode friendly_name: The friendly_name - :param bool reachability_webhooks_enabled: The reachability_webhooks_enabled - :param bool acl_enabled: The acl_enabled - - :returns: Updated ServiceInstance - :rtype: twilio.rest.preview.sync.service.ServiceInstance - """ - data = values.of({ - 'WebhookUrl': webhook_url, - 'FriendlyName': friendly_name, - 'ReachabilityWebhooksEnabled': reachability_webhooks_enabled, - 'AclEnabled': acl_enabled, - }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) - - @property - def documents(self): - """ - Access the documents - - :returns: twilio.rest.preview.sync.service.document.DocumentList - :rtype: twilio.rest.preview.sync.service.document.DocumentList - """ - if self._documents is None: - self._documents = DocumentList(self._version, service_sid=self._solution['sid'], ) - return self._documents - - @property - def sync_lists(self): - """ - Access the sync_lists - - :returns: twilio.rest.preview.sync.service.sync_list.SyncListList - :rtype: twilio.rest.preview.sync.service.sync_list.SyncListList - """ - if self._sync_lists is None: - self._sync_lists = SyncListList(self._version, service_sid=self._solution['sid'], ) - return self._sync_lists - - @property - def sync_maps(self): - """ - Access the sync_maps - - :returns: twilio.rest.preview.sync.service.sync_map.SyncMapList - :rtype: twilio.rest.preview.sync.service.sync_map.SyncMapList - """ - if self._sync_maps is None: - self._sync_maps = SyncMapList(self._version, service_sid=self._solution['sid'], ) - return self._sync_maps - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class ServiceInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, sid=None): - """ - Initialize the ServiceInstance - - :returns: twilio.rest.preview.sync.service.ServiceInstance - :rtype: twilio.rest.preview.sync.service.ServiceInstance - """ - super(ServiceInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'friendly_name': payload['friendly_name'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - 'webhook_url': payload['webhook_url'], - 'reachability_webhooks_enabled': payload['reachability_webhooks_enabled'], - 'acl_enabled': payload['acl_enabled'], - 'links': payload['links'], - } - - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.sync.service.ServiceContext - """ - if self._context is None: - self._context = ServiceContext(self._version, sid=self._solution['sid'], ) - return self._context - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def webhook_url(self): - """ - :returns: The webhook_url - :rtype: unicode - """ - return self._properties['webhook_url'] - - @property - def reachability_webhooks_enabled(self): - """ - :returns: The reachability_webhooks_enabled - :rtype: bool - """ - return self._properties['reachability_webhooks_enabled'] - - @property - def acl_enabled(self): - """ - :returns: The acl_enabled - :rtype: bool - """ - return self._properties['acl_enabled'] - - @property - def links(self): - """ - :returns: The links - :rtype: unicode - """ - return self._properties['links'] - - def fetch(self): - """ - Fetch a ServiceInstance - - :returns: Fetched ServiceInstance - :rtype: twilio.rest.preview.sync.service.ServiceInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the ServiceInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def update(self, webhook_url=values.unset, friendly_name=values.unset, - reachability_webhooks_enabled=values.unset, - acl_enabled=values.unset): - """ - Update the ServiceInstance - - :param unicode webhook_url: The webhook_url - :param unicode friendly_name: The friendly_name - :param bool reachability_webhooks_enabled: The reachability_webhooks_enabled - :param bool acl_enabled: The acl_enabled - - :returns: Updated ServiceInstance - :rtype: twilio.rest.preview.sync.service.ServiceInstance - """ - return self._proxy.update( - webhook_url=webhook_url, - friendly_name=friendly_name, - reachability_webhooks_enabled=reachability_webhooks_enabled, - acl_enabled=acl_enabled, - ) - - @property - def documents(self): - """ - Access the documents - - :returns: twilio.rest.preview.sync.service.document.DocumentList - :rtype: twilio.rest.preview.sync.service.document.DocumentList - """ - return self._proxy.documents - - @property - def sync_lists(self): - """ - Access the sync_lists - - :returns: twilio.rest.preview.sync.service.sync_list.SyncListList - :rtype: twilio.rest.preview.sync.service.sync_list.SyncListList - """ - return self._proxy.sync_lists - - @property - def sync_maps(self): - """ - Access the sync_maps - - :returns: twilio.rest.preview.sync.service.sync_map.SyncMapList - :rtype: twilio.rest.preview.sync.service.sync_map.SyncMapList - """ - return self._proxy.sync_maps - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/sync/service/document/__init__.py b/twilio/rest/preview/sync/service/document/__init__.py deleted file mode 100644 index 527331e497..0000000000 --- a/twilio/rest/preview/sync/service/document/__init__.py +++ /dev/null @@ -1,507 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import serialize -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.page import Page -from twilio.rest.preview.sync.service.document.document_permission import DocumentPermissionList - - -class DocumentList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid): - """ - Initialize the DocumentList - - :param Version version: Version that contains the resource - :param service_sid: The service_sid - - :returns: twilio.rest.preview.sync.service.document.DocumentList - :rtype: twilio.rest.preview.sync.service.document.DocumentList - """ - super(DocumentList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Documents'.format(**self._solution) - - def create(self, unique_name=values.unset, data=values.unset): - """ - Create a new DocumentInstance - - :param unicode unique_name: The unique_name - :param dict data: The data - - :returns: Newly created DocumentInstance - :rtype: twilio.rest.preview.sync.service.document.DocumentInstance - """ - data = values.of({'UniqueName': unique_name, 'Data': serialize.object(data), }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return DocumentInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def stream(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.document.DocumentInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.document.DocumentInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of DocumentInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of DocumentInstance - :rtype: twilio.rest.preview.sync.service.document.DocumentPage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return DocumentPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of DocumentInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of DocumentInstance - :rtype: twilio.rest.preview.sync.service.document.DocumentPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return DocumentPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a DocumentContext - - :param sid: The sid - - :returns: twilio.rest.preview.sync.service.document.DocumentContext - :rtype: twilio.rest.preview.sync.service.document.DocumentContext - """ - return DocumentContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a DocumentContext - - :param sid: The sid - - :returns: twilio.rest.preview.sync.service.document.DocumentContext - :rtype: twilio.rest.preview.sync.service.document.DocumentContext - """ - return DocumentContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class DocumentPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the DocumentPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - - :returns: twilio.rest.preview.sync.service.document.DocumentPage - :rtype: twilio.rest.preview.sync.service.document.DocumentPage - """ - super(DocumentPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of DocumentInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.sync.service.document.DocumentInstance - :rtype: twilio.rest.preview.sync.service.document.DocumentInstance - """ - return DocumentInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class DocumentContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid, sid): - """ - Initialize the DocumentContext - - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: The sid - - :returns: twilio.rest.preview.sync.service.document.DocumentContext - :rtype: twilio.rest.preview.sync.service.document.DocumentContext - """ - super(DocumentContext, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Documents/{sid}'.format(**self._solution) - - # Dependents - self._document_permissions = None - - def fetch(self): - """ - Fetch a DocumentInstance - - :returns: Fetched DocumentInstance - :rtype: twilio.rest.preview.sync.service.document.DocumentInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return DocumentInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the DocumentInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def update(self, data): - """ - Update the DocumentInstance - - :param dict data: The data - - :returns: Updated DocumentInstance - :rtype: twilio.rest.preview.sync.service.document.DocumentInstance - """ - data = values.of({'Data': serialize.object(data), }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return DocumentInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - - @property - def document_permissions(self): - """ - Access the document_permissions - - :returns: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionList - :rtype: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionList - """ - if self._document_permissions is None: - self._document_permissions = DocumentPermissionList( - self._version, - service_sid=self._solution['service_sid'], - document_sid=self._solution['sid'], - ) - return self._document_permissions - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class DocumentInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the DocumentInstance - - :returns: twilio.rest.preview.sync.service.document.DocumentInstance - :rtype: twilio.rest.preview.sync.service.document.DocumentInstance - """ - super(DocumentInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'unique_name': payload['unique_name'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'url': payload['url'], - 'links': payload['links'], - 'revision': payload['revision'], - 'data': payload['data'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'created_by': payload['created_by'], - } - - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.sync.service.document.DocumentContext - """ - if self._context is None: - self._context = DocumentContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] - - @property - def unique_name(self): - """ - :returns: The unique_name - :rtype: unicode - """ - return self._properties['unique_name'] - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def links(self): - """ - :returns: The links - :rtype: unicode - """ - return self._properties['links'] - - @property - def revision(self): - """ - :returns: The revision - :rtype: unicode - """ - return self._properties['revision'] - - @property - def data(self): - """ - :returns: The data - :rtype: dict - """ - return self._properties['data'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def created_by(self): - """ - :returns: The created_by - :rtype: unicode - """ - return self._properties['created_by'] - - def fetch(self): - """ - Fetch a DocumentInstance - - :returns: Fetched DocumentInstance - :rtype: twilio.rest.preview.sync.service.document.DocumentInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the DocumentInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def update(self, data): - """ - Update the DocumentInstance - - :param dict data: The data - - :returns: Updated DocumentInstance - :rtype: twilio.rest.preview.sync.service.document.DocumentInstance - """ - return self._proxy.update(data, ) - - @property - def document_permissions(self): - """ - Access the document_permissions - - :returns: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionList - :rtype: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionList - """ - return self._proxy.document_permissions - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/sync/service/document/document_permission.py b/twilio/rest/preview/sync/service/document/document_permission.py deleted file mode 100644 index 4947708f19..0000000000 --- a/twilio/rest/preview/sync/service/document/document_permission.py +++ /dev/null @@ -1,457 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -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.page import Page - - -class DocumentPermissionList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid, document_sid): - """ - Initialize the DocumentPermissionList - - :param Version version: Version that contains the resource - :param service_sid: Sync Service Instance SID. - :param document_sid: Sync Document SID. - - :returns: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionList - :rtype: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionList - """ - super(DocumentPermissionList, self).__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=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of DocumentPermissionInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of DocumentPermissionInstance - :rtype: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionPage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return DocumentPermissionPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of DocumentPermissionInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of DocumentPermissionInstance - :rtype: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return DocumentPermissionPage(self._version, response, self._solution) - - def get(self, identity): - """ - Constructs a DocumentPermissionContext - - :param identity: Identity of the user to whom the Sync Document Permission applies. - - :returns: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionContext - :rtype: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionContext - """ - return DocumentPermissionContext( - self._version, - service_sid=self._solution['service_sid'], - document_sid=self._solution['document_sid'], - identity=identity, - ) - - def __call__(self, identity): - """ - Constructs a DocumentPermissionContext - - :param identity: Identity of the user to whom the Sync Document Permission applies. - - :returns: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionContext - :rtype: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionContext - """ - return DocumentPermissionContext( - self._version, - service_sid=self._solution['service_sid'], - document_sid=self._solution['document_sid'], - identity=identity, - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class DocumentPermissionPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the DocumentPermissionPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Sync Service Instance SID. - :param document_sid: Sync Document SID. - - :returns: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionPage - :rtype: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionPage - """ - super(DocumentPermissionPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of DocumentPermissionInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionInstance - :rtype: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionInstance - """ - return DocumentPermissionInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - document_sid=self._solution['document_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class DocumentPermissionContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid, document_sid, identity): - """ - Initialize the DocumentPermissionContext - - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param document_sid: Sync Document SID or unique name. - :param identity: Identity of the user to whom the Sync Document Permission applies. - - :returns: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionContext - :rtype: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionContext - """ - super(DocumentPermissionContext, self).__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 fetch(self): - """ - Fetch a DocumentPermissionInstance - - :returns: Fetched DocumentPermissionInstance - :rtype: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return DocumentPermissionInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - document_sid=self._solution['document_sid'], - identity=self._solution['identity'], - ) - - def delete(self): - """ - Deletes the DocumentPermissionInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def update(self, read, write, manage): - """ - Update the DocumentPermissionInstance - - :param bool read: Read access. - :param bool write: Write access. - :param bool manage: Manage access. - - :returns: Updated DocumentPermissionInstance - :rtype: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionInstance - """ - data = values.of({'Read': read, 'Write': write, 'Manage': manage, }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return DocumentPermissionInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - document_sid=self._solution['document_sid'], - identity=self._solution['identity'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class DocumentPermissionInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, service_sid, document_sid, identity=None): - """ - Initialize the DocumentPermissionInstance - - :returns: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionInstance - :rtype: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionInstance - """ - super(DocumentPermissionInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'document_sid': payload['document_sid'], - 'identity': payload['identity'], - 'read': payload['read'], - 'write': payload['write'], - 'manage': payload['manage'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'document_sid': document_sid, - 'identity': identity or self._properties['identity'], - } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionContext - """ - 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 - - @property - def account_sid(self): - """ - :returns: Twilio Account SID. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def service_sid(self): - """ - :returns: Sync Service Instance SID. - :rtype: unicode - """ - return self._properties['service_sid'] - - @property - def document_sid(self): - """ - :returns: Sync Document SID. - :rtype: unicode - """ - return self._properties['document_sid'] - - @property - def identity(self): - """ - :returns: Identity of the user to whom the Sync Document Permission applies. - :rtype: unicode - """ - return self._properties['identity'] - - @property - def read(self): - """ - :returns: Read access. - :rtype: bool - """ - return self._properties['read'] - - @property - def write(self): - """ - :returns: Write access. - :rtype: bool - """ - return self._properties['write'] - - @property - def manage(self): - """ - :returns: Manage access. - :rtype: bool - """ - return self._properties['manage'] - - @property - def url(self): - """ - :returns: URL of this Sync Document Permission. - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch a DocumentPermissionInstance - - :returns: Fetched DocumentPermissionInstance - :rtype: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the DocumentPermissionInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def update(self, read, write, manage): - """ - Update the DocumentPermissionInstance - - :param bool read: Read access. - :param bool write: Write access. - :param bool manage: Manage access. - - :returns: Updated DocumentPermissionInstance - :rtype: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionInstance - """ - return self._proxy.update(read, write, manage, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/sync/service/sync_list/__init__.py b/twilio/rest/preview/sync/service/sync_list/__init__.py deleted file mode 100644 index 6d2f193f3c..0000000000 --- a/twilio/rest/preview/sync/service/sync_list/__init__.py +++ /dev/null @@ -1,489 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page -from twilio.rest.preview.sync.service.sync_list.sync_list_item import SyncListItemList -from twilio.rest.preview.sync.service.sync_list.sync_list_permission import SyncListPermissionList - - -class SyncListList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid): - """ - Initialize the SyncListList - - :param Version version: Version that contains the resource - :param service_sid: The service_sid - - :returns: twilio.rest.preview.sync.service.sync_list.SyncListList - :rtype: twilio.rest.preview.sync.service.sync_list.SyncListList - """ - super(SyncListList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Lists'.format(**self._solution) - - def create(self, unique_name=values.unset): - """ - Create a new SyncListInstance - - :param unicode unique_name: The unique_name - - :returns: Newly created SyncListInstance - :rtype: twilio.rest.preview.sync.service.sync_list.SyncListInstance - """ - data = values.of({'UniqueName': unique_name, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return SyncListInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def stream(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.sync_list.SyncListInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.sync_list.SyncListInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of SyncListInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncListInstance - :rtype: twilio.rest.preview.sync.service.sync_list.SyncListPage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return SyncListPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of SyncListInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of SyncListInstance - :rtype: twilio.rest.preview.sync.service.sync_list.SyncListPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return SyncListPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a SyncListContext - - :param sid: The sid - - :returns: twilio.rest.preview.sync.service.sync_list.SyncListContext - :rtype: twilio.rest.preview.sync.service.sync_list.SyncListContext - """ - return SyncListContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a SyncListContext - - :param sid: The sid - - :returns: twilio.rest.preview.sync.service.sync_list.SyncListContext - :rtype: twilio.rest.preview.sync.service.sync_list.SyncListContext - """ - return SyncListContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SyncListPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the SyncListPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - - :returns: twilio.rest.preview.sync.service.sync_list.SyncListPage - :rtype: twilio.rest.preview.sync.service.sync_list.SyncListPage - """ - super(SyncListPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of SyncListInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.sync.service.sync_list.SyncListInstance - :rtype: twilio.rest.preview.sync.service.sync_list.SyncListInstance - """ - return SyncListInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SyncListContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid, sid): - """ - Initialize the SyncListContext - - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: The sid - - :returns: twilio.rest.preview.sync.service.sync_list.SyncListContext - :rtype: twilio.rest.preview.sync.service.sync_list.SyncListContext - """ - super(SyncListContext, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Lists/{sid}'.format(**self._solution) - - # Dependents - self._sync_list_items = None - self._sync_list_permissions = None - - def fetch(self): - """ - Fetch a SyncListInstance - - :returns: Fetched SyncListInstance - :rtype: twilio.rest.preview.sync.service.sync_list.SyncListInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return SyncListInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the SyncListInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - @property - def sync_list_items(self): - """ - Access the sync_list_items - - :returns: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemList - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemList - """ - if self._sync_list_items is None: - self._sync_list_items = SyncListItemList( - self._version, - service_sid=self._solution['service_sid'], - list_sid=self._solution['sid'], - ) - return self._sync_list_items - - @property - def sync_list_permissions(self): - """ - Access the sync_list_permissions - - :returns: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionList - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionList - """ - if self._sync_list_permissions is None: - self._sync_list_permissions = SyncListPermissionList( - self._version, - service_sid=self._solution['service_sid'], - list_sid=self._solution['sid'], - ) - return self._sync_list_permissions - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class SyncListInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the SyncListInstance - - :returns: twilio.rest.preview.sync.service.sync_list.SyncListInstance - :rtype: twilio.rest.preview.sync.service.sync_list.SyncListInstance - """ - super(SyncListInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'unique_name': payload['unique_name'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'url': payload['url'], - 'links': payload['links'], - 'revision': payload['revision'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'created_by': payload['created_by'], - } - - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.sync.service.sync_list.SyncListContext - """ - if self._context is None: - self._context = SyncListContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] - - @property - def unique_name(self): - """ - :returns: The unique_name - :rtype: unicode - """ - return self._properties['unique_name'] - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def links(self): - """ - :returns: The links - :rtype: unicode - """ - return self._properties['links'] - - @property - def revision(self): - """ - :returns: The revision - :rtype: unicode - """ - return self._properties['revision'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def created_by(self): - """ - :returns: The created_by - :rtype: unicode - """ - return self._properties['created_by'] - - def fetch(self): - """ - Fetch a SyncListInstance - - :returns: Fetched SyncListInstance - :rtype: twilio.rest.preview.sync.service.sync_list.SyncListInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the SyncListInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - @property - def sync_list_items(self): - """ - Access the sync_list_items - - :returns: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemList - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemList - """ - return self._proxy.sync_list_items - - @property - def sync_list_permissions(self): - """ - Access the sync_list_permissions - - :returns: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionList - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionList - """ - return self._proxy.sync_list_permissions - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/sync/service/sync_list/sync_list_item.py b/twilio/rest/preview/sync/service/sync_list/sync_list_item.py deleted file mode 100644 index a3e719070b..0000000000 --- a/twilio/rest/preview/sync/service/sync_list/sync_list_item.py +++ /dev/null @@ -1,524 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import serialize -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.page import Page - - -class SyncListItemList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid, list_sid): - """ - Initialize the SyncListItemList - - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param list_sid: The list_sid - - :returns: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemList - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemList - """ - super(SyncListItemList, self).__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): - """ - Create a new SyncListItemInstance - - :param dict data: The data - - :returns: Newly created SyncListItemInstance - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemInstance - """ - data = values.of({'Data': serialize.object(data), }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return SyncListItemInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - ) - - def stream(self, order=values.unset, from_=values.unset, bounds=values.unset, - limit=None, page_size=None): - """ - 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: The order - :param unicode from_: The from - :param SyncListItemInstance.QueryFromBoundType bounds: The bounds - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemInstance] - """ - 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'], limits['page_limit']) - - def list(self, order=values.unset, from_=values.unset, bounds=values.unset, - limit=None, page_size=None): - """ - 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: The order - :param unicode from_: The from - :param SyncListItemInstance.QueryFromBoundType bounds: The bounds - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemInstance] - """ - return list(self.stream(order=order, from_=from_, bounds=bounds, limit=limit, page_size=page_size, )) - - def page(self, order=values.unset, from_=values.unset, bounds=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of SyncListItemInstance records from the API. - Request is executed immediately - - :param SyncListItemInstance.QueryResultOrder order: The order - :param unicode from_: The from - :param SyncListItemInstance.QueryFromBoundType bounds: The bounds - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncListItemInstance - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemPage - """ - params = values.of({ - 'Order': order, - 'From': from_, - 'Bounds': bounds, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return SyncListItemPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of SyncListItemInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of SyncListItemInstance - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return SyncListItemPage(self._version, response, self._solution) - - def get(self, index): - """ - Constructs a SyncListItemContext - - :param index: The index - - :returns: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemContext - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemContext - """ - return SyncListItemContext( - self._version, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - index=index, - ) - - def __call__(self, index): - """ - Constructs a SyncListItemContext - - :param index: The index - - :returns: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemContext - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemContext - """ - return SyncListItemContext( - self._version, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - index=index, - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SyncListItemPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the SyncListItemPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :param list_sid: The list_sid - - :returns: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemPage - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemPage - """ - super(SyncListItemPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of SyncListItemInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemInstance - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemInstance - """ - return SyncListItemInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SyncListItemContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid, list_sid, index): - """ - Initialize the SyncListItemContext - - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param list_sid: The list_sid - :param index: The index - - :returns: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemContext - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemContext - """ - super(SyncListItemContext, self).__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 fetch(self): - """ - Fetch a SyncListItemInstance - - :returns: Fetched SyncListItemInstance - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return SyncListItemInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - index=self._solution['index'], - ) - - def delete(self): - """ - Deletes the SyncListItemInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def update(self, data): - """ - Update the SyncListItemInstance - - :param dict data: The data - - :returns: Updated SyncListItemInstance - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemInstance - """ - data = values.of({'Data': serialize.object(data), }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return SyncListItemInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - index=self._solution['index'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class SyncListItemInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - class QueryResultOrder(object): - ASC = "asc" - DESC = "desc" - - class QueryFromBoundType(object): - INCLUSIVE = "inclusive" - EXCLUSIVE = "exclusive" - - def __init__(self, version, payload, service_sid, list_sid, index=None): - """ - Initialize the SyncListItemInstance - - :returns: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemInstance - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemInstance - """ - super(SyncListItemInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'index': deserialize.integer(payload['index']), - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'list_sid': payload['list_sid'], - 'url': payload['url'], - 'revision': payload['revision'], - 'data': payload['data'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'created_by': payload['created_by'], - } - - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'list_sid': list_sid, - 'index': index or self._properties['index'], - } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemContext - """ - 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 - - @property - def index(self): - """ - :returns: The index - :rtype: unicode - """ - return self._properties['index'] - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] - - @property - def list_sid(self): - """ - :returns: The list_sid - :rtype: unicode - """ - return self._properties['list_sid'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def revision(self): - """ - :returns: The revision - :rtype: unicode - """ - return self._properties['revision'] - - @property - def data(self): - """ - :returns: The data - :rtype: dict - """ - return self._properties['data'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def created_by(self): - """ - :returns: The created_by - :rtype: unicode - """ - return self._properties['created_by'] - - def fetch(self): - """ - Fetch a SyncListItemInstance - - :returns: Fetched SyncListItemInstance - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the SyncListItemInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def update(self, data): - """ - Update the SyncListItemInstance - - :param dict data: The data - - :returns: Updated SyncListItemInstance - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemInstance - """ - return self._proxy.update(data, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/sync/service/sync_list/sync_list_permission.py b/twilio/rest/preview/sync/service/sync_list/sync_list_permission.py deleted file mode 100644 index 0e612e2fc4..0000000000 --- a/twilio/rest/preview/sync/service/sync_list/sync_list_permission.py +++ /dev/null @@ -1,457 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -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.page import Page - - -class SyncListPermissionList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid, list_sid): - """ - Initialize the SyncListPermissionList - - :param Version version: Version that contains the resource - :param service_sid: Sync Service Instance SID. - :param list_sid: Sync List SID. - - :returns: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionList - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionList - """ - super(SyncListPermissionList, self).__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=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of SyncListPermissionInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncListPermissionInstance - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionPage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return SyncListPermissionPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of SyncListPermissionInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of SyncListPermissionInstance - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return SyncListPermissionPage(self._version, response, self._solution) - - def get(self, identity): - """ - Constructs a SyncListPermissionContext - - :param identity: Identity of the user to whom the Sync List Permission applies. - - :returns: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionContext - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionContext - """ - return SyncListPermissionContext( - self._version, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - identity=identity, - ) - - def __call__(self, identity): - """ - Constructs a SyncListPermissionContext - - :param identity: Identity of the user to whom the Sync List Permission applies. - - :returns: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionContext - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionContext - """ - return SyncListPermissionContext( - self._version, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - identity=identity, - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SyncListPermissionPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the SyncListPermissionPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Sync Service Instance SID. - :param list_sid: Sync List SID. - - :returns: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionPage - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionPage - """ - super(SyncListPermissionPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of SyncListPermissionInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionInstance - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionInstance - """ - return SyncListPermissionInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SyncListPermissionContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid, list_sid, identity): - """ - Initialize the SyncListPermissionContext - - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param list_sid: Sync List SID or unique name. - :param identity: Identity of the user to whom the Sync List Permission applies. - - :returns: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionContext - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionContext - """ - super(SyncListPermissionContext, self).__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 fetch(self): - """ - Fetch a SyncListPermissionInstance - - :returns: Fetched SyncListPermissionInstance - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return SyncListPermissionInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - identity=self._solution['identity'], - ) - - def delete(self): - """ - Deletes the SyncListPermissionInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def update(self, read, write, manage): - """ - Update the SyncListPermissionInstance - - :param bool read: Read access. - :param bool write: Write access. - :param bool manage: Manage access. - - :returns: Updated SyncListPermissionInstance - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionInstance - """ - data = values.of({'Read': read, 'Write': write, 'Manage': manage, }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return SyncListPermissionInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - identity=self._solution['identity'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class SyncListPermissionInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, service_sid, list_sid, identity=None): - """ - Initialize the SyncListPermissionInstance - - :returns: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionInstance - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionInstance - """ - super(SyncListPermissionInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'list_sid': payload['list_sid'], - 'identity': payload['identity'], - 'read': payload['read'], - 'write': payload['write'], - 'manage': payload['manage'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'list_sid': list_sid, - 'identity': identity or self._properties['identity'], - } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionContext - """ - 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 - - @property - def account_sid(self): - """ - :returns: Twilio Account SID. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def service_sid(self): - """ - :returns: Sync Service Instance SID. - :rtype: unicode - """ - return self._properties['service_sid'] - - @property - def list_sid(self): - """ - :returns: Sync List SID. - :rtype: unicode - """ - return self._properties['list_sid'] - - @property - def identity(self): - """ - :returns: Identity of the user to whom the Sync List Permission applies. - :rtype: unicode - """ - return self._properties['identity'] - - @property - def read(self): - """ - :returns: Read access. - :rtype: bool - """ - return self._properties['read'] - - @property - def write(self): - """ - :returns: Write access. - :rtype: bool - """ - return self._properties['write'] - - @property - def manage(self): - """ - :returns: Manage access. - :rtype: bool - """ - return self._properties['manage'] - - @property - def url(self): - """ - :returns: URL of this Sync List Permission. - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch a SyncListPermissionInstance - - :returns: Fetched SyncListPermissionInstance - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the SyncListPermissionInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def update(self, read, write, manage): - """ - Update the SyncListPermissionInstance - - :param bool read: Read access. - :param bool write: Write access. - :param bool manage: Manage access. - - :returns: Updated SyncListPermissionInstance - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionInstance - """ - return self._proxy.update(read, write, manage, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/sync/service/sync_map/__init__.py b/twilio/rest/preview/sync/service/sync_map/__init__.py deleted file mode 100644 index 4cfc5d544f..0000000000 --- a/twilio/rest/preview/sync/service/sync_map/__init__.py +++ /dev/null @@ -1,489 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page -from twilio.rest.preview.sync.service.sync_map.sync_map_item import SyncMapItemList -from twilio.rest.preview.sync.service.sync_map.sync_map_permission import SyncMapPermissionList - - -class SyncMapList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid): - """ - Initialize the SyncMapList - - :param Version version: Version that contains the resource - :param service_sid: The service_sid - - :returns: twilio.rest.preview.sync.service.sync_map.SyncMapList - :rtype: twilio.rest.preview.sync.service.sync_map.SyncMapList - """ - super(SyncMapList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Maps'.format(**self._solution) - - def create(self, unique_name=values.unset): - """ - Create a new SyncMapInstance - - :param unicode unique_name: The unique_name - - :returns: Newly created SyncMapInstance - :rtype: twilio.rest.preview.sync.service.sync_map.SyncMapInstance - """ - data = values.of({'UniqueName': unique_name, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return SyncMapInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def stream(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.sync_map.SyncMapInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.sync_map.SyncMapInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of SyncMapInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncMapInstance - :rtype: twilio.rest.preview.sync.service.sync_map.SyncMapPage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return SyncMapPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of SyncMapInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of SyncMapInstance - :rtype: twilio.rest.preview.sync.service.sync_map.SyncMapPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return SyncMapPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a SyncMapContext - - :param sid: The sid - - :returns: twilio.rest.preview.sync.service.sync_map.SyncMapContext - :rtype: twilio.rest.preview.sync.service.sync_map.SyncMapContext - """ - return SyncMapContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a SyncMapContext - - :param sid: The sid - - :returns: twilio.rest.preview.sync.service.sync_map.SyncMapContext - :rtype: twilio.rest.preview.sync.service.sync_map.SyncMapContext - """ - return SyncMapContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SyncMapPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the SyncMapPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - - :returns: twilio.rest.preview.sync.service.sync_map.SyncMapPage - :rtype: twilio.rest.preview.sync.service.sync_map.SyncMapPage - """ - super(SyncMapPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of SyncMapInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.sync.service.sync_map.SyncMapInstance - :rtype: twilio.rest.preview.sync.service.sync_map.SyncMapInstance - """ - return SyncMapInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SyncMapContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid, sid): - """ - Initialize the SyncMapContext - - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: The sid - - :returns: twilio.rest.preview.sync.service.sync_map.SyncMapContext - :rtype: twilio.rest.preview.sync.service.sync_map.SyncMapContext - """ - super(SyncMapContext, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Maps/{sid}'.format(**self._solution) - - # Dependents - self._sync_map_items = None - self._sync_map_permissions = None - - def fetch(self): - """ - Fetch a SyncMapInstance - - :returns: Fetched SyncMapInstance - :rtype: twilio.rest.preview.sync.service.sync_map.SyncMapInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return SyncMapInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the SyncMapInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - @property - def sync_map_items(self): - """ - Access the sync_map_items - - :returns: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemList - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemList - """ - if self._sync_map_items is None: - self._sync_map_items = SyncMapItemList( - self._version, - service_sid=self._solution['service_sid'], - map_sid=self._solution['sid'], - ) - return self._sync_map_items - - @property - def sync_map_permissions(self): - """ - Access the sync_map_permissions - - :returns: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionList - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionList - """ - if self._sync_map_permissions is None: - self._sync_map_permissions = SyncMapPermissionList( - self._version, - service_sid=self._solution['service_sid'], - map_sid=self._solution['sid'], - ) - return self._sync_map_permissions - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class SyncMapInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the SyncMapInstance - - :returns: twilio.rest.preview.sync.service.sync_map.SyncMapInstance - :rtype: twilio.rest.preview.sync.service.sync_map.SyncMapInstance - """ - super(SyncMapInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'unique_name': payload['unique_name'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'url': payload['url'], - 'links': payload['links'], - 'revision': payload['revision'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'created_by': payload['created_by'], - } - - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.sync.service.sync_map.SyncMapContext - """ - if self._context is None: - self._context = SyncMapContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] - - @property - def unique_name(self): - """ - :returns: The unique_name - :rtype: unicode - """ - return self._properties['unique_name'] - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def links(self): - """ - :returns: The links - :rtype: unicode - """ - return self._properties['links'] - - @property - def revision(self): - """ - :returns: The revision - :rtype: unicode - """ - return self._properties['revision'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def created_by(self): - """ - :returns: The created_by - :rtype: unicode - """ - return self._properties['created_by'] - - def fetch(self): - """ - Fetch a SyncMapInstance - - :returns: Fetched SyncMapInstance - :rtype: twilio.rest.preview.sync.service.sync_map.SyncMapInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the SyncMapInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - @property - def sync_map_items(self): - """ - Access the sync_map_items - - :returns: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemList - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemList - """ - return self._proxy.sync_map_items - - @property - def sync_map_permissions(self): - """ - Access the sync_map_permissions - - :returns: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionList - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionList - """ - return self._proxy.sync_map_permissions - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/sync/service/sync_map/sync_map_item.py b/twilio/rest/preview/sync/service/sync_map/sync_map_item.py deleted file mode 100644 index 079dd9ddb7..0000000000 --- a/twilio/rest/preview/sync/service/sync_map/sync_map_item.py +++ /dev/null @@ -1,525 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import serialize -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.page import Page - - -class SyncMapItemList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid, map_sid): - """ - Initialize the SyncMapItemList - - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param map_sid: The map_sid - - :returns: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemList - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemList - """ - super(SyncMapItemList, self).__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, data): - """ - Create a new SyncMapItemInstance - - :param unicode key: The key - :param dict data: The data - - :returns: Newly created SyncMapItemInstance - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemInstance - """ - data = values.of({'Key': key, 'Data': serialize.object(data), }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return SyncMapItemInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - ) - - def stream(self, order=values.unset, from_=values.unset, bounds=values.unset, - limit=None, page_size=None): - """ - 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: The order - :param unicode from_: The from - :param SyncMapItemInstance.QueryFromBoundType bounds: The bounds - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemInstance] - """ - 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'], limits['page_limit']) - - def list(self, order=values.unset, from_=values.unset, bounds=values.unset, - limit=None, page_size=None): - """ - 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: The order - :param unicode from_: The from - :param SyncMapItemInstance.QueryFromBoundType bounds: The bounds - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemInstance] - """ - return list(self.stream(order=order, from_=from_, bounds=bounds, limit=limit, page_size=page_size, )) - - def page(self, order=values.unset, from_=values.unset, bounds=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of SyncMapItemInstance records from the API. - Request is executed immediately - - :param SyncMapItemInstance.QueryResultOrder order: The order - :param unicode from_: The from - :param SyncMapItemInstance.QueryFromBoundType bounds: The bounds - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncMapItemInstance - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemPage - """ - params = values.of({ - 'Order': order, - 'From': from_, - 'Bounds': bounds, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return SyncMapItemPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of SyncMapItemInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of SyncMapItemInstance - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return SyncMapItemPage(self._version, response, self._solution) - - def get(self, key): - """ - Constructs a SyncMapItemContext - - :param key: The key - - :returns: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemContext - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemContext - """ - return SyncMapItemContext( - self._version, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - key=key, - ) - - def __call__(self, key): - """ - Constructs a SyncMapItemContext - - :param key: The key - - :returns: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemContext - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemContext - """ - return SyncMapItemContext( - self._version, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - key=key, - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SyncMapItemPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the SyncMapItemPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :param map_sid: The map_sid - - :returns: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemPage - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemPage - """ - super(SyncMapItemPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of SyncMapItemInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemInstance - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemInstance - """ - return SyncMapItemInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SyncMapItemContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid, map_sid, key): - """ - Initialize the SyncMapItemContext - - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param map_sid: The map_sid - :param key: The key - - :returns: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemContext - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemContext - """ - super(SyncMapItemContext, self).__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 fetch(self): - """ - Fetch a SyncMapItemInstance - - :returns: Fetched SyncMapItemInstance - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return SyncMapItemInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - key=self._solution['key'], - ) - - def delete(self): - """ - Deletes the SyncMapItemInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def update(self, data): - """ - Update the SyncMapItemInstance - - :param dict data: The data - - :returns: Updated SyncMapItemInstance - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemInstance - """ - data = values.of({'Data': serialize.object(data), }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return SyncMapItemInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - key=self._solution['key'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class SyncMapItemInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - class QueryResultOrder(object): - ASC = "asc" - DESC = "desc" - - class QueryFromBoundType(object): - INCLUSIVE = "inclusive" - EXCLUSIVE = "exclusive" - - def __init__(self, version, payload, service_sid, map_sid, key=None): - """ - Initialize the SyncMapItemInstance - - :returns: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemInstance - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemInstance - """ - super(SyncMapItemInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'key': payload['key'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'map_sid': payload['map_sid'], - 'url': payload['url'], - 'revision': payload['revision'], - 'data': payload['data'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'created_by': payload['created_by'], - } - - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'map_sid': map_sid, - 'key': key or self._properties['key'], - } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemContext - """ - 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 - - @property - def key(self): - """ - :returns: The key - :rtype: unicode - """ - return self._properties['key'] - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] - - @property - def map_sid(self): - """ - :returns: The map_sid - :rtype: unicode - """ - return self._properties['map_sid'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def revision(self): - """ - :returns: The revision - :rtype: unicode - """ - return self._properties['revision'] - - @property - def data(self): - """ - :returns: The data - :rtype: dict - """ - return self._properties['data'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def created_by(self): - """ - :returns: The created_by - :rtype: unicode - """ - return self._properties['created_by'] - - def fetch(self): - """ - Fetch a SyncMapItemInstance - - :returns: Fetched SyncMapItemInstance - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the SyncMapItemInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def update(self, data): - """ - Update the SyncMapItemInstance - - :param dict data: The data - - :returns: Updated SyncMapItemInstance - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemInstance - """ - return self._proxy.update(data, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/sync/service/sync_map/sync_map_permission.py b/twilio/rest/preview/sync/service/sync_map/sync_map_permission.py deleted file mode 100644 index 794ea9d751..0000000000 --- a/twilio/rest/preview/sync/service/sync_map/sync_map_permission.py +++ /dev/null @@ -1,457 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -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.page import Page - - -class SyncMapPermissionList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid, map_sid): - """ - Initialize the SyncMapPermissionList - - :param Version version: Version that contains the resource - :param service_sid: Sync Service Instance SID. - :param map_sid: Sync Map SID. - - :returns: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionList - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionList - """ - super(SyncMapPermissionList, self).__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=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of SyncMapPermissionInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncMapPermissionInstance - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionPage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return SyncMapPermissionPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of SyncMapPermissionInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of SyncMapPermissionInstance - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return SyncMapPermissionPage(self._version, response, self._solution) - - def get(self, identity): - """ - Constructs a SyncMapPermissionContext - - :param identity: Identity of the user to whom the Sync Map Permission applies. - - :returns: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionContext - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionContext - """ - return SyncMapPermissionContext( - self._version, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - identity=identity, - ) - - def __call__(self, identity): - """ - Constructs a SyncMapPermissionContext - - :param identity: Identity of the user to whom the Sync Map Permission applies. - - :returns: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionContext - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionContext - """ - return SyncMapPermissionContext( - self._version, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - identity=identity, - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SyncMapPermissionPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the SyncMapPermissionPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Sync Service Instance SID. - :param map_sid: Sync Map SID. - - :returns: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionPage - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionPage - """ - super(SyncMapPermissionPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of SyncMapPermissionInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionInstance - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionInstance - """ - return SyncMapPermissionInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SyncMapPermissionContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, service_sid, map_sid, identity): - """ - Initialize the SyncMapPermissionContext - - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param map_sid: Sync Map SID or unique name. - :param identity: Identity of the user to whom the Sync Map Permission applies. - - :returns: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionContext - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionContext - """ - super(SyncMapPermissionContext, self).__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 fetch(self): - """ - Fetch a SyncMapPermissionInstance - - :returns: Fetched SyncMapPermissionInstance - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return SyncMapPermissionInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - identity=self._solution['identity'], - ) - - def delete(self): - """ - Deletes the SyncMapPermissionInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def update(self, read, write, manage): - """ - Update the SyncMapPermissionInstance - - :param bool read: Read access. - :param bool write: Write access. - :param bool manage: Manage access. - - :returns: Updated SyncMapPermissionInstance - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionInstance - """ - data = values.of({'Read': read, 'Write': write, 'Manage': manage, }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return SyncMapPermissionInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - identity=self._solution['identity'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class SyncMapPermissionInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, service_sid, map_sid, identity=None): - """ - Initialize the SyncMapPermissionInstance - - :returns: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionInstance - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionInstance - """ - super(SyncMapPermissionInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'map_sid': payload['map_sid'], - 'identity': payload['identity'], - 'read': payload['read'], - 'write': payload['write'], - 'manage': payload['manage'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'map_sid': map_sid, - 'identity': identity or self._properties['identity'], - } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionContext - """ - 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 - - @property - def account_sid(self): - """ - :returns: Twilio Account SID. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def service_sid(self): - """ - :returns: Sync Service Instance SID. - :rtype: unicode - """ - return self._properties['service_sid'] - - @property - def map_sid(self): - """ - :returns: Sync Map SID. - :rtype: unicode - """ - return self._properties['map_sid'] - - @property - def identity(self): - """ - :returns: Identity of the user to whom the Sync Map Permission applies. - :rtype: unicode - """ - return self._properties['identity'] - - @property - def read(self): - """ - :returns: Read access. - :rtype: bool - """ - return self._properties['read'] - - @property - def write(self): - """ - :returns: Write access. - :rtype: bool - """ - return self._properties['write'] - - @property - def manage(self): - """ - :returns: Manage access. - :rtype: bool - """ - return self._properties['manage'] - - @property - def url(self): - """ - :returns: URL of this Sync Map Permission. - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch a SyncMapPermissionInstance - - :returns: Fetched SyncMapPermissionInstance - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the SyncMapPermissionInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def update(self, read, write, manage): - """ - Update the SyncMapPermissionInstance - - :param bool read: Read access. - :param bool write: Write access. - :param bool manage: Manage access. - - :returns: Updated SyncMapPermissionInstance - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionInstance - """ - return self._proxy.update(read, write, manage, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/understand/__init__.py b/twilio/rest/preview/understand/__init__.py deleted file mode 100644 index 42e3823546..0000000000 --- a/twilio/rest/preview/understand/__init__.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base.version import Version -from twilio.rest.preview.understand.assistant import AssistantList - - -class Understand(Version): - - def __init__(self, domain): - """ - Initialize the Understand version of Preview - - :returns: Understand version of Preview - :rtype: twilio.rest.preview.understand.Understand.Understand - """ - super(Understand, self).__init__(domain) - self.version = 'understand' - self._assistants = None - - @property - def assistants(self): - """ - :rtype: twilio.rest.preview.understand.assistant.AssistantList - """ - if self._assistants is None: - self._assistants = AssistantList(self) - return self._assistants - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/preview/understand/assistant/__init__.py b/twilio/rest/preview/understand/assistant/__init__.py deleted file mode 100644 index dfbde64ed2..0000000000 --- a/twilio/rest/preview/understand/assistant/__init__.py +++ /dev/null @@ -1,634 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page -from twilio.rest.preview.understand.assistant.field_type import FieldTypeList -from twilio.rest.preview.understand.assistant.intent import IntentList -from twilio.rest.preview.understand.assistant.model_build import ModelBuildList -from twilio.rest.preview.understand.assistant.query import QueryList - - -class AssistantList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version): - """ - Initialize the AssistantList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.preview.understand.assistant.AssistantList - :rtype: twilio.rest.preview.understand.assistant.AssistantList - """ - super(AssistantList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Assistants'.format(**self._solution) - - def stream(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.understand.assistant.AssistantInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.understand.assistant.AssistantInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of AssistantInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of AssistantInstance - :rtype: twilio.rest.preview.understand.assistant.AssistantPage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return AssistantPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of AssistantInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of AssistantInstance - :rtype: twilio.rest.preview.understand.assistant.AssistantPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return AssistantPage(self._version, response, self._solution) - - def create(self, friendly_name=values.unset, log_queries=values.unset, - ttl=values.unset, unique_name=values.unset, - response_url=values.unset, callback_url=values.unset, - callback_events=values.unset): - """ - Create a new AssistantInstance - - :param unicode friendly_name: The friendly_name - :param bool log_queries: The log_queries - :param unicode ttl: The ttl - :param unicode unique_name: The unique_name - :param unicode response_url: The response_url - :param unicode callback_url: The callback_url - :param unicode callback_events: The callback_events - - :returns: Newly created AssistantInstance - :rtype: twilio.rest.preview.understand.assistant.AssistantInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'LogQueries': log_queries, - 'Ttl': ttl, - 'UniqueName': unique_name, - 'ResponseUrl': response_url, - 'CallbackUrl': callback_url, - 'CallbackEvents': callback_events, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return AssistantInstance(self._version, payload, ) - - def get(self, sid): - """ - Constructs a AssistantContext - - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.AssistantContext - :rtype: twilio.rest.preview.understand.assistant.AssistantContext - """ - return AssistantContext(self._version, sid=sid, ) - - def __call__(self, sid): - """ - Constructs a AssistantContext - - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.AssistantContext - :rtype: twilio.rest.preview.understand.assistant.AssistantContext - """ - return AssistantContext(self._version, sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class AssistantPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the AssistantPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.preview.understand.assistant.AssistantPage - :rtype: twilio.rest.preview.understand.assistant.AssistantPage - """ - super(AssistantPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of AssistantInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.understand.assistant.AssistantInstance - :rtype: twilio.rest.preview.understand.assistant.AssistantInstance - """ - return AssistantInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class AssistantContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, sid): - """ - Initialize the AssistantContext - - :param Version version: Version that contains the resource - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.AssistantContext - :rtype: twilio.rest.preview.understand.assistant.AssistantContext - """ - super(AssistantContext, self).__init__(version) - - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Assistants/{sid}'.format(**self._solution) - - # Dependents - self._field_types = None - self._intents = None - self._model_builds = None - self._queries = None - - def fetch(self): - """ - Fetch a AssistantInstance - - :returns: Fetched AssistantInstance - :rtype: twilio.rest.preview.understand.assistant.AssistantInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return AssistantInstance(self._version, payload, sid=self._solution['sid'], ) - - def update(self, friendly_name=values.unset, log_queries=values.unset, - ttl=values.unset, unique_name=values.unset, - response_url=values.unset, callback_url=values.unset, - callback_events=values.unset): - """ - Update the AssistantInstance - - :param unicode friendly_name: The friendly_name - :param bool log_queries: The log_queries - :param unicode ttl: The ttl - :param unicode unique_name: The unique_name - :param unicode response_url: The response_url - :param unicode callback_url: The callback_url - :param unicode callback_events: The callback_events - - :returns: Updated AssistantInstance - :rtype: twilio.rest.preview.understand.assistant.AssistantInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'LogQueries': log_queries, - 'Ttl': ttl, - 'UniqueName': unique_name, - 'ResponseUrl': response_url, - 'CallbackUrl': callback_url, - 'CallbackEvents': callback_events, - }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return AssistantInstance(self._version, payload, sid=self._solution['sid'], ) - - def delete(self): - """ - Deletes the AssistantInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - @property - def field_types(self): - """ - Access the field_types - - :returns: twilio.rest.preview.understand.assistant.field_type.FieldTypeList - :rtype: twilio.rest.preview.understand.assistant.field_type.FieldTypeList - """ - if self._field_types is None: - self._field_types = FieldTypeList(self._version, assistant_sid=self._solution['sid'], ) - return self._field_types - - @property - def intents(self): - """ - Access the intents - - :returns: twilio.rest.preview.understand.assistant.intent.IntentList - :rtype: twilio.rest.preview.understand.assistant.intent.IntentList - """ - if self._intents is None: - self._intents = IntentList(self._version, assistant_sid=self._solution['sid'], ) - return self._intents - - @property - def model_builds(self): - """ - Access the model_builds - - :returns: twilio.rest.preview.understand.assistant.model_build.ModelBuildList - :rtype: twilio.rest.preview.understand.assistant.model_build.ModelBuildList - """ - if self._model_builds is None: - self._model_builds = ModelBuildList(self._version, assistant_sid=self._solution['sid'], ) - return self._model_builds - - @property - def queries(self): - """ - Access the queries - - :returns: twilio.rest.preview.understand.assistant.query.QueryList - :rtype: twilio.rest.preview.understand.assistant.query.QueryList - """ - if self._queries is None: - self._queries = QueryList(self._version, assistant_sid=self._solution['sid'], ) - return self._queries - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class AssistantInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, sid=None): - """ - Initialize the AssistantInstance - - :returns: twilio.rest.preview.understand.assistant.AssistantInstance - :rtype: twilio.rest.preview.understand.assistant.AssistantInstance - """ - super(AssistantInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'friendly_name': payload['friendly_name'], - 'latest_model_build_sid': payload['latest_model_build_sid'], - 'links': payload['links'], - 'log_queries': payload['log_queries'], - 'sid': payload['sid'], - 'ttl': deserialize.integer(payload['ttl']), - 'unique_name': payload['unique_name'], - 'url': payload['url'], - 'response_url': payload['response_url'], - 'callback_url': payload['callback_url'], - 'callback_events': payload['callback_events'], - } - - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.understand.assistant.AssistantContext - """ - if self._context is None: - self._context = AssistantContext(self._version, sid=self._solution['sid'], ) - return self._context - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def latest_model_build_sid(self): - """ - :returns: The latest_model_build_sid - :rtype: unicode - """ - return self._properties['latest_model_build_sid'] - - @property - def links(self): - """ - :returns: The links - :rtype: unicode - """ - return self._properties['links'] - - @property - def log_queries(self): - """ - :returns: The log_queries - :rtype: bool - """ - return self._properties['log_queries'] - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] - - @property - def ttl(self): - """ - :returns: The ttl - :rtype: unicode - """ - return self._properties['ttl'] - - @property - def unique_name(self): - """ - :returns: The unique_name - :rtype: unicode - """ - return self._properties['unique_name'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def response_url(self): - """ - :returns: The response_url - :rtype: unicode - """ - return self._properties['response_url'] - - @property - def callback_url(self): - """ - :returns: The callback_url - :rtype: unicode - """ - return self._properties['callback_url'] - - @property - def callback_events(self): - """ - :returns: The callback_events - :rtype: unicode - """ - return self._properties['callback_events'] - - def fetch(self): - """ - Fetch a AssistantInstance - - :returns: Fetched AssistantInstance - :rtype: twilio.rest.preview.understand.assistant.AssistantInstance - """ - return self._proxy.fetch() - - def update(self, friendly_name=values.unset, log_queries=values.unset, - ttl=values.unset, unique_name=values.unset, - response_url=values.unset, callback_url=values.unset, - callback_events=values.unset): - """ - Update the AssistantInstance - - :param unicode friendly_name: The friendly_name - :param bool log_queries: The log_queries - :param unicode ttl: The ttl - :param unicode unique_name: The unique_name - :param unicode response_url: The response_url - :param unicode callback_url: The callback_url - :param unicode callback_events: The callback_events - - :returns: Updated AssistantInstance - :rtype: twilio.rest.preview.understand.assistant.AssistantInstance - """ - return self._proxy.update( - friendly_name=friendly_name, - log_queries=log_queries, - ttl=ttl, - unique_name=unique_name, - response_url=response_url, - callback_url=callback_url, - callback_events=callback_events, - ) - - def delete(self): - """ - Deletes the AssistantInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - @property - def field_types(self): - """ - Access the field_types - - :returns: twilio.rest.preview.understand.assistant.field_type.FieldTypeList - :rtype: twilio.rest.preview.understand.assistant.field_type.FieldTypeList - """ - return self._proxy.field_types - - @property - def intents(self): - """ - Access the intents - - :returns: twilio.rest.preview.understand.assistant.intent.IntentList - :rtype: twilio.rest.preview.understand.assistant.intent.IntentList - """ - return self._proxy.intents - - @property - def model_builds(self): - """ - Access the model_builds - - :returns: twilio.rest.preview.understand.assistant.model_build.ModelBuildList - :rtype: twilio.rest.preview.understand.assistant.model_build.ModelBuildList - """ - return self._proxy.model_builds - - @property - def queries(self): - """ - Access the queries - - :returns: twilio.rest.preview.understand.assistant.query.QueryList - :rtype: twilio.rest.preview.understand.assistant.query.QueryList - """ - return self._proxy.queries - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/understand/assistant/field_type/__init__.py b/twilio/rest/preview/understand/assistant/field_type/__init__.py deleted file mode 100644 index 1ba72169e8..0000000000 --- a/twilio/rest/preview/understand/assistant/field_type/__init__.py +++ /dev/null @@ -1,490 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page -from twilio.rest.preview.understand.assistant.field_type.field_value import FieldValueList - - -class FieldTypeList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, assistant_sid): - """ - Initialize the FieldTypeList - - :param Version version: Version that contains the resource - :param assistant_sid: The assistant_sid - - :returns: twilio.rest.preview.understand.assistant.field_type.FieldTypeList - :rtype: twilio.rest.preview.understand.assistant.field_type.FieldTypeList - """ - super(FieldTypeList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, } - self._uri = '/Assistants/{assistant_sid}/FieldTypes'.format(**self._solution) - - def stream(self, limit=None, page_size=None): - """ - Streams FieldTypeInstance records from the API as a generator stream. - This operation lazily loads 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 limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.understand.assistant.field_type.FieldTypeInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists FieldTypeInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.understand.assistant.field_type.FieldTypeInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of FieldTypeInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of FieldTypeInstance - :rtype: twilio.rest.preview.understand.assistant.field_type.FieldTypePage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return FieldTypePage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of FieldTypeInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of FieldTypeInstance - :rtype: twilio.rest.preview.understand.assistant.field_type.FieldTypePage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return FieldTypePage(self._version, response, self._solution) - - def create(self, unique_name, friendly_name=values.unset): - """ - Create a new FieldTypeInstance - - :param unicode unique_name: The unique_name - :param unicode friendly_name: The friendly_name - - :returns: Newly created FieldTypeInstance - :rtype: twilio.rest.preview.understand.assistant.field_type.FieldTypeInstance - """ - data = values.of({'UniqueName': unique_name, 'FriendlyName': friendly_name, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return FieldTypeInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], ) - - def get(self, sid): - """ - Constructs a FieldTypeContext - - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.field_type.FieldTypeContext - :rtype: twilio.rest.preview.understand.assistant.field_type.FieldTypeContext - """ - return FieldTypeContext(self._version, assistant_sid=self._solution['assistant_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a FieldTypeContext - - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.field_type.FieldTypeContext - :rtype: twilio.rest.preview.understand.assistant.field_type.FieldTypeContext - """ - return FieldTypeContext(self._version, assistant_sid=self._solution['assistant_sid'], sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class FieldTypePage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the FieldTypePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param assistant_sid: The assistant_sid - - :returns: twilio.rest.preview.understand.assistant.field_type.FieldTypePage - :rtype: twilio.rest.preview.understand.assistant.field_type.FieldTypePage - """ - super(FieldTypePage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of FieldTypeInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.understand.assistant.field_type.FieldTypeInstance - :rtype: twilio.rest.preview.understand.assistant.field_type.FieldTypeInstance - """ - return FieldTypeInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class FieldTypeContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, assistant_sid, sid): - """ - Initialize the FieldTypeContext - - :param Version version: Version that contains the resource - :param assistant_sid: The assistant_sid - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.field_type.FieldTypeContext - :rtype: twilio.rest.preview.understand.assistant.field_type.FieldTypeContext - """ - super(FieldTypeContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'sid': sid, } - self._uri = '/Assistants/{assistant_sid}/FieldTypes/{sid}'.format(**self._solution) - - # Dependents - self._field_values = None - - def fetch(self): - """ - Fetch a FieldTypeInstance - - :returns: Fetched FieldTypeInstance - :rtype: twilio.rest.preview.understand.assistant.field_type.FieldTypeInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return FieldTypeInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - sid=self._solution['sid'], - ) - - def update(self, friendly_name=values.unset, unique_name=values.unset): - """ - Update the FieldTypeInstance - - :param unicode friendly_name: The friendly_name - :param unicode unique_name: The unique_name - - :returns: Updated FieldTypeInstance - :rtype: twilio.rest.preview.understand.assistant.field_type.FieldTypeInstance - """ - data = values.of({'FriendlyName': friendly_name, 'UniqueName': unique_name, }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return FieldTypeInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the FieldTypeInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - @property - def field_values(self): - """ - Access the field_values - - :returns: twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueList - :rtype: twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueList - """ - if self._field_values is None: - self._field_values = FieldValueList( - self._version, - assistant_sid=self._solution['assistant_sid'], - field_type_sid=self._solution['sid'], - ) - return self._field_values - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class FieldTypeInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, assistant_sid, sid=None): - """ - Initialize the FieldTypeInstance - - :returns: twilio.rest.preview.understand.assistant.field_type.FieldTypeInstance - :rtype: twilio.rest.preview.understand.assistant.field_type.FieldTypeInstance - """ - super(FieldTypeInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'friendly_name': payload['friendly_name'], - 'links': payload['links'], - 'assistant_sid': payload['assistant_sid'], - 'sid': payload['sid'], - 'unique_name': payload['unique_name'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = {'assistant_sid': assistant_sid, 'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: FieldTypeContext for this FieldTypeInstance - :rtype: twilio.rest.preview.understand.assistant.field_type.FieldTypeContext - """ - if self._context is None: - self._context = FieldTypeContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def links(self): - """ - :returns: The links - :rtype: unicode - """ - return self._properties['links'] - - @property - def assistant_sid(self): - """ - :returns: The assistant_sid - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] - - @property - def unique_name(self): - """ - :returns: The unique_name - :rtype: unicode - """ - return self._properties['unique_name'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch a FieldTypeInstance - - :returns: Fetched FieldTypeInstance - :rtype: twilio.rest.preview.understand.assistant.field_type.FieldTypeInstance - """ - return self._proxy.fetch() - - def update(self, friendly_name=values.unset, unique_name=values.unset): - """ - Update the FieldTypeInstance - - :param unicode friendly_name: The friendly_name - :param unicode unique_name: The unique_name - - :returns: Updated FieldTypeInstance - :rtype: twilio.rest.preview.understand.assistant.field_type.FieldTypeInstance - """ - return self._proxy.update(friendly_name=friendly_name, unique_name=unique_name, ) - - def delete(self): - """ - Deletes the FieldTypeInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - @property - def field_values(self): - """ - Access the field_values - - :returns: twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueList - :rtype: twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueList - """ - return self._proxy.field_values - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/understand/assistant/field_type/field_value.py b/twilio/rest/preview/understand/assistant/field_type/field_value.py deleted file mode 100644 index d9b86f2786..0000000000 --- a/twilio/rest/preview/understand/assistant/field_type/field_value.py +++ /dev/null @@ -1,470 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page - - -class FieldValueList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, assistant_sid, field_type_sid): - """ - Initialize the FieldValueList - - :param Version version: Version that contains the resource - :param assistant_sid: The assistant_sid - :param field_type_sid: The field_type_sid - - :returns: twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueList - :rtype: twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueList - """ - super(FieldValueList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'field_type_sid': field_type_sid, } - self._uri = '/Assistants/{assistant_sid}/FieldTypes/{field_type_sid}/FieldValues'.format(**self._solution) - - def stream(self, language=values.unset, limit=None, page_size=None): - """ - Streams FieldValueInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param unicode language: The language - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(language=language, page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, language=values.unset, limit=None, page_size=None): - """ - Lists FieldValueInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param unicode language: The language - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueInstance] - """ - return list(self.stream(language=language, limit=limit, page_size=page_size, )) - - def page(self, language=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of FieldValueInstance records from the API. - Request is executed immediately - - :param unicode language: The language - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of FieldValueInstance - :rtype: twilio.rest.preview.understand.assistant.field_type.field_value.FieldValuePage - """ - params = values.of({ - 'Language': language, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return FieldValuePage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of FieldValueInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of FieldValueInstance - :rtype: twilio.rest.preview.understand.assistant.field_type.field_value.FieldValuePage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return FieldValuePage(self._version, response, self._solution) - - def create(self, language, value, synonym_of=values.unset): - """ - Create a new FieldValueInstance - - :param unicode language: The language - :param unicode value: The value - :param unicode synonym_of: The synonym_of - - :returns: Newly created FieldValueInstance - :rtype: twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueInstance - """ - data = values.of({'Language': language, 'Value': value, 'SynonymOf': synonym_of, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return FieldValueInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - field_type_sid=self._solution['field_type_sid'], - ) - - def get(self, sid): - """ - Constructs a FieldValueContext - - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueContext - :rtype: twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueContext - """ - return FieldValueContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - field_type_sid=self._solution['field_type_sid'], - sid=sid, - ) - - def __call__(self, sid): - """ - Constructs a FieldValueContext - - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueContext - :rtype: twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueContext - """ - return FieldValueContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - field_type_sid=self._solution['field_type_sid'], - sid=sid, - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class FieldValuePage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the FieldValuePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param assistant_sid: The assistant_sid - :param field_type_sid: The field_type_sid - - :returns: twilio.rest.preview.understand.assistant.field_type.field_value.FieldValuePage - :rtype: twilio.rest.preview.understand.assistant.field_type.field_value.FieldValuePage - """ - super(FieldValuePage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of FieldValueInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueInstance - :rtype: twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueInstance - """ - return FieldValueInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - field_type_sid=self._solution['field_type_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class FieldValueContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, assistant_sid, field_type_sid, sid): - """ - Initialize the FieldValueContext - - :param Version version: Version that contains the resource - :param assistant_sid: The assistant_sid - :param field_type_sid: The field_type_sid - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueContext - :rtype: twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueContext - """ - super(FieldValueContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'field_type_sid': field_type_sid, 'sid': sid, } - self._uri = '/Assistants/{assistant_sid}/FieldTypes/{field_type_sid}/FieldValues/{sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch a FieldValueInstance - - :returns: Fetched FieldValueInstance - :rtype: twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return FieldValueInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - field_type_sid=self._solution['field_type_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the FieldValueInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class FieldValueInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, assistant_sid, field_type_sid, sid=None): - """ - Initialize the FieldValueInstance - - :returns: twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueInstance - :rtype: twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueInstance - """ - super(FieldValueInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'field_type_sid': payload['field_type_sid'], - 'language': payload['language'], - 'assistant_sid': payload['assistant_sid'], - 'sid': payload['sid'], - 'value': payload['value'], - 'url': payload['url'], - 'synonym_of': payload['synonym_of'], - } - - # Context - self._context = None - self._solution = { - 'assistant_sid': assistant_sid, - 'field_type_sid': field_type_sid, - 'sid': sid or self._properties['sid'], - } - - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: FieldValueContext for this FieldValueInstance - :rtype: twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueContext - """ - if self._context is None: - self._context = FieldValueContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - field_type_sid=self._solution['field_type_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def field_type_sid(self): - """ - :returns: The field_type_sid - :rtype: unicode - """ - return self._properties['field_type_sid'] - - @property - def language(self): - """ - :returns: The language - :rtype: unicode - """ - return self._properties['language'] - - @property - def assistant_sid(self): - """ - :returns: The assistant_sid - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] - - @property - def value(self): - """ - :returns: The value - :rtype: unicode - """ - return self._properties['value'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def synonym_of(self): - """ - :returns: The synonym_of - :rtype: unicode - """ - return self._properties['synonym_of'] - - def fetch(self): - """ - Fetch a FieldValueInstance - - :returns: Fetched FieldValueInstance - :rtype: twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the FieldValueInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/understand/assistant/intent/__init__.py b/twilio/rest/preview/understand/assistant/intent/__init__.py deleted file mode 100644 index fe37491d1d..0000000000 --- a/twilio/rest/preview/understand/assistant/intent/__init__.py +++ /dev/null @@ -1,518 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page -from twilio.rest.preview.understand.assistant.intent.field import FieldList -from twilio.rest.preview.understand.assistant.intent.sample import SampleList - - -class IntentList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, assistant_sid): - """ - Initialize the IntentList - - :param Version version: Version that contains the resource - :param assistant_sid: The assistant_sid - - :returns: twilio.rest.preview.understand.assistant.intent.IntentList - :rtype: twilio.rest.preview.understand.assistant.intent.IntentList - """ - super(IntentList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, } - self._uri = '/Assistants/{assistant_sid}/Intents'.format(**self._solution) - - def stream(self, limit=None, page_size=None): - """ - Streams IntentInstance records from the API as a generator stream. - This operation lazily loads 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 limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.understand.assistant.intent.IntentInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists IntentInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.understand.assistant.intent.IntentInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of IntentInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of IntentInstance - :rtype: twilio.rest.preview.understand.assistant.intent.IntentPage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return IntentPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of IntentInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of IntentInstance - :rtype: twilio.rest.preview.understand.assistant.intent.IntentPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return IntentPage(self._version, response, self._solution) - - def create(self, unique_name, friendly_name=values.unset): - """ - Create a new IntentInstance - - :param unicode unique_name: The unique_name - :param unicode friendly_name: The friendly_name - - :returns: Newly created IntentInstance - :rtype: twilio.rest.preview.understand.assistant.intent.IntentInstance - """ - data = values.of({'UniqueName': unique_name, 'FriendlyName': friendly_name, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return IntentInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], ) - - def get(self, sid): - """ - Constructs a IntentContext - - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.intent.IntentContext - :rtype: twilio.rest.preview.understand.assistant.intent.IntentContext - """ - return IntentContext(self._version, assistant_sid=self._solution['assistant_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a IntentContext - - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.intent.IntentContext - :rtype: twilio.rest.preview.understand.assistant.intent.IntentContext - """ - return IntentContext(self._version, assistant_sid=self._solution['assistant_sid'], sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class IntentPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the IntentPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param assistant_sid: The assistant_sid - - :returns: twilio.rest.preview.understand.assistant.intent.IntentPage - :rtype: twilio.rest.preview.understand.assistant.intent.IntentPage - """ - super(IntentPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of IntentInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.understand.assistant.intent.IntentInstance - :rtype: twilio.rest.preview.understand.assistant.intent.IntentInstance - """ - return IntentInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class IntentContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, assistant_sid, sid): - """ - Initialize the IntentContext - - :param Version version: Version that contains the resource - :param assistant_sid: The assistant_sid - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.intent.IntentContext - :rtype: twilio.rest.preview.understand.assistant.intent.IntentContext - """ - super(IntentContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'sid': sid, } - self._uri = '/Assistants/{assistant_sid}/Intents/{sid}'.format(**self._solution) - - # Dependents - self._fields = None - self._samples = None - - def fetch(self): - """ - Fetch a IntentInstance - - :returns: Fetched IntentInstance - :rtype: twilio.rest.preview.understand.assistant.intent.IntentInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return IntentInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - sid=self._solution['sid'], - ) - - def update(self, friendly_name=values.unset, unique_name=values.unset): - """ - Update the IntentInstance - - :param unicode friendly_name: The friendly_name - :param unicode unique_name: The unique_name - - :returns: Updated IntentInstance - :rtype: twilio.rest.preview.understand.assistant.intent.IntentInstance - """ - data = values.of({'FriendlyName': friendly_name, 'UniqueName': unique_name, }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return IntentInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the IntentInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - @property - def fields(self): - """ - Access the fields - - :returns: twilio.rest.preview.understand.assistant.intent.field.FieldList - :rtype: twilio.rest.preview.understand.assistant.intent.field.FieldList - """ - if self._fields is None: - self._fields = FieldList( - self._version, - assistant_sid=self._solution['assistant_sid'], - intent_sid=self._solution['sid'], - ) - return self._fields - - @property - def samples(self): - """ - Access the samples - - :returns: twilio.rest.preview.understand.assistant.intent.sample.SampleList - :rtype: twilio.rest.preview.understand.assistant.intent.sample.SampleList - """ - if self._samples is None: - self._samples = SampleList( - self._version, - assistant_sid=self._solution['assistant_sid'], - intent_sid=self._solution['sid'], - ) - return self._samples - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class IntentInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, assistant_sid, sid=None): - """ - Initialize the IntentInstance - - :returns: twilio.rest.preview.understand.assistant.intent.IntentInstance - :rtype: twilio.rest.preview.understand.assistant.intent.IntentInstance - """ - super(IntentInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'friendly_name': payload['friendly_name'], - 'links': payload['links'], - 'assistant_sid': payload['assistant_sid'], - 'sid': payload['sid'], - 'unique_name': payload['unique_name'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = {'assistant_sid': assistant_sid, 'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: IntentContext for this IntentInstance - :rtype: twilio.rest.preview.understand.assistant.intent.IntentContext - """ - if self._context is None: - self._context = IntentContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def links(self): - """ - :returns: The links - :rtype: unicode - """ - return self._properties['links'] - - @property - def assistant_sid(self): - """ - :returns: The assistant_sid - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] - - @property - def unique_name(self): - """ - :returns: The unique_name - :rtype: unicode - """ - return self._properties['unique_name'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch a IntentInstance - - :returns: Fetched IntentInstance - :rtype: twilio.rest.preview.understand.assistant.intent.IntentInstance - """ - return self._proxy.fetch() - - def update(self, friendly_name=values.unset, unique_name=values.unset): - """ - Update the IntentInstance - - :param unicode friendly_name: The friendly_name - :param unicode unique_name: The unique_name - - :returns: Updated IntentInstance - :rtype: twilio.rest.preview.understand.assistant.intent.IntentInstance - """ - return self._proxy.update(friendly_name=friendly_name, unique_name=unique_name, ) - - def delete(self): - """ - Deletes the IntentInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - @property - def fields(self): - """ - Access the fields - - :returns: twilio.rest.preview.understand.assistant.intent.field.FieldList - :rtype: twilio.rest.preview.understand.assistant.intent.field.FieldList - """ - return self._proxy.fields - - @property - def samples(self): - """ - Access the samples - - :returns: twilio.rest.preview.understand.assistant.intent.sample.SampleList - :rtype: twilio.rest.preview.understand.assistant.intent.sample.SampleList - """ - return self._proxy.samples - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/understand/assistant/intent/field.py b/twilio/rest/preview/understand/assistant/intent/field.py deleted file mode 100644 index aa786cb483..0000000000 --- a/twilio/rest/preview/understand/assistant/intent/field.py +++ /dev/null @@ -1,452 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page - - -class FieldList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, assistant_sid, intent_sid): - """ - Initialize the FieldList - - :param Version version: Version that contains the resource - :param assistant_sid: The assistant_sid - :param intent_sid: The intent_sid - - :returns: twilio.rest.preview.understand.assistant.intent.field.FieldList - :rtype: twilio.rest.preview.understand.assistant.intent.field.FieldList - """ - super(FieldList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'intent_sid': intent_sid, } - self._uri = '/Assistants/{assistant_sid}/Intents/{intent_sid}/Fields'.format(**self._solution) - - def stream(self, limit=None, page_size=None): - """ - Streams FieldInstance records from the API as a generator stream. - This operation lazily loads 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 limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.understand.assistant.intent.field.FieldInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists FieldInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.understand.assistant.intent.field.FieldInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of FieldInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of FieldInstance - :rtype: twilio.rest.preview.understand.assistant.intent.field.FieldPage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return FieldPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of FieldInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of FieldInstance - :rtype: twilio.rest.preview.understand.assistant.intent.field.FieldPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return FieldPage(self._version, response, self._solution) - - def create(self, field_type, unique_name): - """ - Create a new FieldInstance - - :param unicode field_type: The field_type - :param unicode unique_name: The unique_name - - :returns: Newly created FieldInstance - :rtype: twilio.rest.preview.understand.assistant.intent.field.FieldInstance - """ - data = values.of({'FieldType': field_type, 'UniqueName': unique_name, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return FieldInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - intent_sid=self._solution['intent_sid'], - ) - - def get(self, sid): - """ - Constructs a FieldContext - - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.intent.field.FieldContext - :rtype: twilio.rest.preview.understand.assistant.intent.field.FieldContext - """ - return FieldContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - intent_sid=self._solution['intent_sid'], - sid=sid, - ) - - def __call__(self, sid): - """ - Constructs a FieldContext - - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.intent.field.FieldContext - :rtype: twilio.rest.preview.understand.assistant.intent.field.FieldContext - """ - return FieldContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - intent_sid=self._solution['intent_sid'], - sid=sid, - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class FieldPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the FieldPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param assistant_sid: The assistant_sid - :param intent_sid: The intent_sid - - :returns: twilio.rest.preview.understand.assistant.intent.field.FieldPage - :rtype: twilio.rest.preview.understand.assistant.intent.field.FieldPage - """ - super(FieldPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of FieldInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.understand.assistant.intent.field.FieldInstance - :rtype: twilio.rest.preview.understand.assistant.intent.field.FieldInstance - """ - return FieldInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - intent_sid=self._solution['intent_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class FieldContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, assistant_sid, intent_sid, sid): - """ - Initialize the FieldContext - - :param Version version: Version that contains the resource - :param assistant_sid: The assistant_sid - :param intent_sid: The intent_sid - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.intent.field.FieldContext - :rtype: twilio.rest.preview.understand.assistant.intent.field.FieldContext - """ - super(FieldContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'intent_sid': intent_sid, 'sid': sid, } - self._uri = '/Assistants/{assistant_sid}/Intents/{intent_sid}/Fields/{sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch a FieldInstance - - :returns: Fetched FieldInstance - :rtype: twilio.rest.preview.understand.assistant.intent.field.FieldInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return FieldInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - intent_sid=self._solution['intent_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the FieldInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class FieldInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, assistant_sid, intent_sid, sid=None): - """ - Initialize the FieldInstance - - :returns: twilio.rest.preview.understand.assistant.intent.field.FieldInstance - :rtype: twilio.rest.preview.understand.assistant.intent.field.FieldInstance - """ - super(FieldInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'field_type': payload['field_type'], - 'intent_sid': payload['intent_sid'], - 'assistant_sid': payload['assistant_sid'], - 'sid': payload['sid'], - 'unique_name': payload['unique_name'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = { - 'assistant_sid': assistant_sid, - 'intent_sid': intent_sid, - 'sid': sid or self._properties['sid'], - } - - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: FieldContext for this FieldInstance - :rtype: twilio.rest.preview.understand.assistant.intent.field.FieldContext - """ - if self._context is None: - self._context = FieldContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - intent_sid=self._solution['intent_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def field_type(self): - """ - :returns: The field_type - :rtype: unicode - """ - return self._properties['field_type'] - - @property - def intent_sid(self): - """ - :returns: The intent_sid - :rtype: unicode - """ - return self._properties['intent_sid'] - - @property - def assistant_sid(self): - """ - :returns: The assistant_sid - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] - - @property - def unique_name(self): - """ - :returns: The unique_name - :rtype: unicode - """ - return self._properties['unique_name'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch a FieldInstance - - :returns: Fetched FieldInstance - :rtype: twilio.rest.preview.understand.assistant.intent.field.FieldInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the FieldInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/understand/assistant/intent/sample.py b/twilio/rest/preview/understand/assistant/intent/sample.py deleted file mode 100644 index 5dd4f47088..0000000000 --- a/twilio/rest/preview/understand/assistant/intent/sample.py +++ /dev/null @@ -1,512 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page - - -class SampleList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, assistant_sid, intent_sid): - """ - Initialize the SampleList - - :param Version version: Version that contains the resource - :param assistant_sid: The assistant_sid - :param intent_sid: The intent_sid - - :returns: twilio.rest.preview.understand.assistant.intent.sample.SampleList - :rtype: twilio.rest.preview.understand.assistant.intent.sample.SampleList - """ - super(SampleList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'intent_sid': intent_sid, } - self._uri = '/Assistants/{assistant_sid}/Intents/{intent_sid}/Samples'.format(**self._solution) - - def stream(self, language=values.unset, limit=None, page_size=None): - """ - Streams SampleInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param unicode language: The language - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.understand.assistant.intent.sample.SampleInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(language=language, page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, language=values.unset, limit=None, page_size=None): - """ - Lists SampleInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param unicode language: The language - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.understand.assistant.intent.sample.SampleInstance] - """ - return list(self.stream(language=language, limit=limit, page_size=page_size, )) - - def page(self, language=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of SampleInstance records from the API. - Request is executed immediately - - :param unicode language: The language - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of SampleInstance - :rtype: twilio.rest.preview.understand.assistant.intent.sample.SamplePage - """ - params = values.of({ - 'Language': language, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return SamplePage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of SampleInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of SampleInstance - :rtype: twilio.rest.preview.understand.assistant.intent.sample.SamplePage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return SamplePage(self._version, response, self._solution) - - def create(self, language, tagged_text, source_channel=values.unset): - """ - Create a new SampleInstance - - :param unicode language: The language - :param unicode tagged_text: The tagged_text - :param unicode source_channel: The source_channel - - :returns: Newly created SampleInstance - :rtype: twilio.rest.preview.understand.assistant.intent.sample.SampleInstance - """ - data = values.of({'Language': language, 'TaggedText': tagged_text, 'SourceChannel': source_channel, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - intent_sid=self._solution['intent_sid'], - ) - - def get(self, sid): - """ - Constructs a SampleContext - - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.intent.sample.SampleContext - :rtype: twilio.rest.preview.understand.assistant.intent.sample.SampleContext - """ - return SampleContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - intent_sid=self._solution['intent_sid'], - sid=sid, - ) - - def __call__(self, sid): - """ - Constructs a SampleContext - - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.intent.sample.SampleContext - :rtype: twilio.rest.preview.understand.assistant.intent.sample.SampleContext - """ - return SampleContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - intent_sid=self._solution['intent_sid'], - sid=sid, - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SamplePage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the SamplePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param assistant_sid: The assistant_sid - :param intent_sid: The intent_sid - - :returns: twilio.rest.preview.understand.assistant.intent.sample.SamplePage - :rtype: twilio.rest.preview.understand.assistant.intent.sample.SamplePage - """ - super(SamplePage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of SampleInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.understand.assistant.intent.sample.SampleInstance - :rtype: twilio.rest.preview.understand.assistant.intent.sample.SampleInstance - """ - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - intent_sid=self._solution['intent_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SampleContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, assistant_sid, intent_sid, sid): - """ - Initialize the SampleContext - - :param Version version: Version that contains the resource - :param assistant_sid: The assistant_sid - :param intent_sid: The intent_sid - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.intent.sample.SampleContext - :rtype: twilio.rest.preview.understand.assistant.intent.sample.SampleContext - """ - super(SampleContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'intent_sid': intent_sid, 'sid': sid, } - self._uri = '/Assistants/{assistant_sid}/Intents/{intent_sid}/Samples/{sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch a SampleInstance - - :returns: Fetched SampleInstance - :rtype: twilio.rest.preview.understand.assistant.intent.sample.SampleInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - intent_sid=self._solution['intent_sid'], - sid=self._solution['sid'], - ) - - def update(self, language=values.unset, tagged_text=values.unset, - source_channel=values.unset): - """ - Update the SampleInstance - - :param unicode language: The language - :param unicode tagged_text: The tagged_text - :param unicode source_channel: The source_channel - - :returns: Updated SampleInstance - :rtype: twilio.rest.preview.understand.assistant.intent.sample.SampleInstance - """ - data = values.of({'Language': language, 'TaggedText': tagged_text, 'SourceChannel': source_channel, }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - intent_sid=self._solution['intent_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the SampleInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class SampleInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, assistant_sid, intent_sid, sid=None): - """ - Initialize the SampleInstance - - :returns: twilio.rest.preview.understand.assistant.intent.sample.SampleInstance - :rtype: twilio.rest.preview.understand.assistant.intent.sample.SampleInstance - """ - super(SampleInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'intent_sid': payload['intent_sid'], - 'language': payload['language'], - 'assistant_sid': payload['assistant_sid'], - 'sid': payload['sid'], - 'tagged_text': payload['tagged_text'], - 'url': payload['url'], - 'source_channel': payload['source_channel'], - } - - # Context - self._context = None - self._solution = { - 'assistant_sid': assistant_sid, - 'intent_sid': intent_sid, - 'sid': sid or self._properties['sid'], - } - - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: SampleContext for this SampleInstance - :rtype: twilio.rest.preview.understand.assistant.intent.sample.SampleContext - """ - if self._context is None: - self._context = SampleContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - intent_sid=self._solution['intent_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def intent_sid(self): - """ - :returns: The intent_sid - :rtype: unicode - """ - return self._properties['intent_sid'] - - @property - def language(self): - """ - :returns: The language - :rtype: unicode - """ - return self._properties['language'] - - @property - def assistant_sid(self): - """ - :returns: The assistant_sid - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] - - @property - def tagged_text(self): - """ - :returns: The tagged_text - :rtype: unicode - """ - return self._properties['tagged_text'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def source_channel(self): - """ - :returns: The source_channel - :rtype: unicode - """ - return self._properties['source_channel'] - - def fetch(self): - """ - Fetch a SampleInstance - - :returns: Fetched SampleInstance - :rtype: twilio.rest.preview.understand.assistant.intent.sample.SampleInstance - """ - return self._proxy.fetch() - - def update(self, language=values.unset, tagged_text=values.unset, - source_channel=values.unset): - """ - Update the SampleInstance - - :param unicode language: The language - :param unicode tagged_text: The tagged_text - :param unicode source_channel: The source_channel - - :returns: Updated SampleInstance - :rtype: twilio.rest.preview.understand.assistant.intent.sample.SampleInstance - """ - return self._proxy.update(language=language, tagged_text=tagged_text, source_channel=source_channel, ) - - def delete(self): - """ - Deletes the SampleInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/understand/assistant/model_build.py b/twilio/rest/preview/understand/assistant/model_build.py deleted file mode 100644 index fbd50a6856..0000000000 --- a/twilio/rest/preview/understand/assistant/model_build.py +++ /dev/null @@ -1,474 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page - - -class ModelBuildList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, assistant_sid): - """ - Initialize the ModelBuildList - - :param Version version: Version that contains the resource - :param assistant_sid: The assistant_sid - - :returns: twilio.rest.preview.understand.assistant.model_build.ModelBuildList - :rtype: twilio.rest.preview.understand.assistant.model_build.ModelBuildList - """ - super(ModelBuildList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, } - self._uri = '/Assistants/{assistant_sid}/ModelBuilds'.format(**self._solution) - - def stream(self, limit=None, page_size=None): - """ - Streams ModelBuildInstance records from the API as a generator stream. - This operation lazily loads 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 limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.understand.assistant.model_build.ModelBuildInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - Lists ModelBuildInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.understand.assistant.model_build.ModelBuildInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of ModelBuildInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of ModelBuildInstance - :rtype: twilio.rest.preview.understand.assistant.model_build.ModelBuildPage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return ModelBuildPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of ModelBuildInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of ModelBuildInstance - :rtype: twilio.rest.preview.understand.assistant.model_build.ModelBuildPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ModelBuildPage(self._version, response, self._solution) - - def create(self, status_callback=values.unset, unique_name=values.unset): - """ - Create a new ModelBuildInstance - - :param unicode status_callback: The status_callback - :param unicode unique_name: The unique_name - - :returns: Newly created ModelBuildInstance - :rtype: twilio.rest.preview.understand.assistant.model_build.ModelBuildInstance - """ - data = values.of({'StatusCallback': status_callback, 'UniqueName': unique_name, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return ModelBuildInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], ) - - def get(self, sid): - """ - Constructs a ModelBuildContext - - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.model_build.ModelBuildContext - :rtype: twilio.rest.preview.understand.assistant.model_build.ModelBuildContext - """ - return ModelBuildContext(self._version, assistant_sid=self._solution['assistant_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a ModelBuildContext - - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.model_build.ModelBuildContext - :rtype: twilio.rest.preview.understand.assistant.model_build.ModelBuildContext - """ - return ModelBuildContext(self._version, assistant_sid=self._solution['assistant_sid'], sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ModelBuildPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the ModelBuildPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param assistant_sid: The assistant_sid - - :returns: twilio.rest.preview.understand.assistant.model_build.ModelBuildPage - :rtype: twilio.rest.preview.understand.assistant.model_build.ModelBuildPage - """ - super(ModelBuildPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of ModelBuildInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.understand.assistant.model_build.ModelBuildInstance - :rtype: twilio.rest.preview.understand.assistant.model_build.ModelBuildInstance - """ - return ModelBuildInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ModelBuildContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, assistant_sid, sid): - """ - Initialize the ModelBuildContext - - :param Version version: Version that contains the resource - :param assistant_sid: The assistant_sid - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.model_build.ModelBuildContext - :rtype: twilio.rest.preview.understand.assistant.model_build.ModelBuildContext - """ - super(ModelBuildContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'sid': sid, } - self._uri = '/Assistants/{assistant_sid}/ModelBuilds/{sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch a ModelBuildInstance - - :returns: Fetched ModelBuildInstance - :rtype: twilio.rest.preview.understand.assistant.model_build.ModelBuildInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return ModelBuildInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - sid=self._solution['sid'], - ) - - def update(self, unique_name=values.unset): - """ - Update the ModelBuildInstance - - :param unicode unique_name: The unique_name - - :returns: Updated ModelBuildInstance - :rtype: twilio.rest.preview.understand.assistant.model_build.ModelBuildInstance - """ - data = values.of({'UniqueName': unique_name, }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return ModelBuildInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the ModelBuildInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class ModelBuildInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - class Status(object): - ENQUEUED = "enqueued" - BUILDING = "building" - COMPLETED = "completed" - FAILED = "failed" - CANCELED = "canceled" - - def __init__(self, version, payload, assistant_sid, sid=None): - """ - Initialize the ModelBuildInstance - - :returns: twilio.rest.preview.understand.assistant.model_build.ModelBuildInstance - :rtype: twilio.rest.preview.understand.assistant.model_build.ModelBuildInstance - """ - super(ModelBuildInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'assistant_sid': payload['assistant_sid'], - 'sid': payload['sid'], - 'status': payload['status'], - 'unique_name': payload['unique_name'], - 'url': payload['url'], - 'build_duration': deserialize.integer(payload['build_duration']), - 'error_code': deserialize.integer(payload['error_code']), - } - - # Context - self._context = None - self._solution = {'assistant_sid': assistant_sid, 'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: ModelBuildContext for this ModelBuildInstance - :rtype: twilio.rest.preview.understand.assistant.model_build.ModelBuildContext - """ - if self._context is None: - self._context = ModelBuildContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def assistant_sid(self): - """ - :returns: The assistant_sid - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] - - @property - def status(self): - """ - :returns: The status - :rtype: ModelBuildInstance.Status - """ - return self._properties['status'] - - @property - def unique_name(self): - """ - :returns: The unique_name - :rtype: unicode - """ - return self._properties['unique_name'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def build_duration(self): - """ - :returns: The build_duration - :rtype: unicode - """ - return self._properties['build_duration'] - - @property - def error_code(self): - """ - :returns: The error_code - :rtype: unicode - """ - return self._properties['error_code'] - - def fetch(self): - """ - Fetch a ModelBuildInstance - - :returns: Fetched ModelBuildInstance - :rtype: twilio.rest.preview.understand.assistant.model_build.ModelBuildInstance - """ - return self._proxy.fetch() - - def update(self, unique_name=values.unset): - """ - Update the ModelBuildInstance - - :param unicode unique_name: The unique_name - - :returns: Updated ModelBuildInstance - :rtype: twilio.rest.preview.understand.assistant.model_build.ModelBuildInstance - """ - return self._proxy.update(unique_name=unique_name, ) - - def delete(self): - """ - Deletes the ModelBuildInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/understand/assistant/query.py b/twilio/rest/preview/understand/assistant/query.py deleted file mode 100644 index 14c25834f6..0000000000 --- a/twilio/rest/preview/understand/assistant/query.py +++ /dev/null @@ -1,536 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page - - -class QueryList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, assistant_sid): - """ - Initialize the QueryList - - :param Version version: Version that contains the resource - :param assistant_sid: The assistant_sid - - :returns: twilio.rest.preview.understand.assistant.query.QueryList - :rtype: twilio.rest.preview.understand.assistant.query.QueryList - """ - super(QueryList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, } - self._uri = '/Assistants/{assistant_sid}/Queries'.format(**self._solution) - - def stream(self, language=values.unset, model_build=values.unset, - status=values.unset, limit=None, page_size=None): - """ - Streams QueryInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param unicode language: The language - :param unicode model_build: The model_build - :param unicode status: The status - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.understand.assistant.query.QueryInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page( - language=language, - model_build=model_build, - status=status, - page_size=limits['page_size'], - ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, language=values.unset, model_build=values.unset, - status=values.unset, limit=None, page_size=None): - """ - Lists QueryInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param unicode language: The language - :param unicode model_build: The model_build - :param unicode status: The status - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.understand.assistant.query.QueryInstance] - """ - return list(self.stream( - language=language, - model_build=model_build, - status=status, - limit=limit, - page_size=page_size, - )) - - def page(self, language=values.unset, model_build=values.unset, - status=values.unset, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of QueryInstance records from the API. - Request is executed immediately - - :param unicode language: The language - :param unicode model_build: The model_build - :param unicode status: The status - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of QueryInstance - :rtype: twilio.rest.preview.understand.assistant.query.QueryPage - """ - params = values.of({ - 'Language': language, - 'ModelBuild': model_build, - 'Status': status, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return QueryPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of QueryInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of QueryInstance - :rtype: twilio.rest.preview.understand.assistant.query.QueryPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return QueryPage(self._version, response, self._solution) - - def create(self, language, query, intents=values.unset, - model_build=values.unset, field=values.unset): - """ - Create a new QueryInstance - - :param unicode language: The language - :param unicode query: The query - :param unicode intents: The intents - :param unicode model_build: The model_build - :param unicode field: The field - - :returns: Newly created QueryInstance - :rtype: twilio.rest.preview.understand.assistant.query.QueryInstance - """ - data = values.of({ - 'Language': language, - 'Query': query, - 'Intents': intents, - 'ModelBuild': model_build, - 'Field': field, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return QueryInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], ) - - def get(self, sid): - """ - Constructs a QueryContext - - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.query.QueryContext - :rtype: twilio.rest.preview.understand.assistant.query.QueryContext - """ - return QueryContext(self._version, assistant_sid=self._solution['assistant_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a QueryContext - - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.query.QueryContext - :rtype: twilio.rest.preview.understand.assistant.query.QueryContext - """ - return QueryContext(self._version, assistant_sid=self._solution['assistant_sid'], sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class QueryPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the QueryPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param assistant_sid: The assistant_sid - - :returns: twilio.rest.preview.understand.assistant.query.QueryPage - :rtype: twilio.rest.preview.understand.assistant.query.QueryPage - """ - super(QueryPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of QueryInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.understand.assistant.query.QueryInstance - :rtype: twilio.rest.preview.understand.assistant.query.QueryInstance - """ - return QueryInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class QueryContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, assistant_sid, sid): - """ - Initialize the QueryContext - - :param Version version: Version that contains the resource - :param assistant_sid: The assistant_sid - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.query.QueryContext - :rtype: twilio.rest.preview.understand.assistant.query.QueryContext - """ - super(QueryContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'sid': sid, } - self._uri = '/Assistants/{assistant_sid}/Queries/{sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch a QueryInstance - - :returns: Fetched QueryInstance - :rtype: twilio.rest.preview.understand.assistant.query.QueryInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return QueryInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - sid=self._solution['sid'], - ) - - def update(self, sample_sid=values.unset, status=values.unset): - """ - Update the QueryInstance - - :param unicode sample_sid: The sample_sid - :param unicode status: The status - - :returns: Updated QueryInstance - :rtype: twilio.rest.preview.understand.assistant.query.QueryInstance - """ - data = values.of({'SampleSid': sample_sid, 'Status': status, }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return QueryInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the QueryInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class QueryInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, assistant_sid, sid=None): - """ - Initialize the QueryInstance - - :returns: twilio.rest.preview.understand.assistant.query.QueryInstance - :rtype: twilio.rest.preview.understand.assistant.query.QueryInstance - """ - super(QueryInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'results': payload['results'], - 'language': payload['language'], - 'model_build_sid': payload['model_build_sid'], - 'query': payload['query'], - 'sample_sid': payload['sample_sid'], - 'assistant_sid': payload['assistant_sid'], - 'sid': payload['sid'], - 'status': payload['status'], - 'url': payload['url'], - 'source_channel': payload['source_channel'], - } - - # Context - self._context = None - self._solution = {'assistant_sid': assistant_sid, 'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: QueryContext for this QueryInstance - :rtype: twilio.rest.preview.understand.assistant.query.QueryContext - """ - if self._context is None: - self._context = QueryContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def results(self): - """ - :returns: The results - :rtype: dict - """ - return self._properties['results'] - - @property - def language(self): - """ - :returns: The language - :rtype: unicode - """ - return self._properties['language'] - - @property - def model_build_sid(self): - """ - :returns: The model_build_sid - :rtype: unicode - """ - return self._properties['model_build_sid'] - - @property - def query(self): - """ - :returns: The query - :rtype: unicode - """ - return self._properties['query'] - - @property - def sample_sid(self): - """ - :returns: The sample_sid - :rtype: unicode - """ - return self._properties['sample_sid'] - - @property - def assistant_sid(self): - """ - :returns: The assistant_sid - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] - - @property - def status(self): - """ - :returns: The status - :rtype: unicode - """ - return self._properties['status'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def source_channel(self): - """ - :returns: The source_channel - :rtype: unicode - """ - return self._properties['source_channel'] - - def fetch(self): - """ - Fetch a QueryInstance - - :returns: Fetched QueryInstance - :rtype: twilio.rest.preview.understand.assistant.query.QueryInstance - """ - return self._proxy.fetch() - - def update(self, sample_sid=values.unset, status=values.unset): - """ - Update the QueryInstance - - :param unicode sample_sid: The sample_sid - :param unicode status: The status - - :returns: Updated QueryInstance - :rtype: twilio.rest.preview.understand.assistant.query.QueryInstance - """ - return self._proxy.update(sample_sid=sample_sid, status=status, ) - - def delete(self): - """ - Deletes the QueryInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/preview/wireless/__init__.py b/twilio/rest/preview/wireless/__init__.py index 72294baef3..85ed4fb54d 100644 --- a/twilio/rest/preview/wireless/__init__.py +++ b/twilio/rest/preview/wireless/__init__.py @@ -1,12 +1,20 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 @@ -14,51 +22,38 @@ class Wireless(Version): - def __init__(self, domain): + def __init__(self, domain: Domain): """ Initialize the Wireless version of Preview - :returns: Wireless version of Preview - :rtype: twilio.rest.preview.wireless.Wireless.Wireless + :param domain: The Twilio.preview domain """ - super(Wireless, self).__init__(domain) - self.version = 'wireless' - self._commands = None - self._rate_plans = None - self._sims = None + super().__init__(domain, "wireless") + self._commands: Optional[CommandList] = None + self._rate_plans: Optional[RatePlanList] = None + self._sims: Optional[SimList] = None @property - def commands(self): - """ - :rtype: twilio.rest.preview.wireless.command.CommandList - """ + def commands(self) -> CommandList: if self._commands is None: self._commands = CommandList(self) return self._commands @property - def rate_plans(self): - """ - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanList - """ + def rate_plans(self) -> RatePlanList: if self._rate_plans is None: self._rate_plans = RatePlanList(self) return self._rate_plans @property - def sims(self): - """ - :rtype: twilio.rest.preview.wireless.sim.SimList - """ + def sims(self) -> SimList: if self._sims is None: self._sims = SimList(self) return self._sims - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/preview/wireless/command.py b/twilio/rest/preview/wireless/command.py index e3d536f75d..8e715e09ef 100644 --- a/twilio/rest/preview/wireless/command.py +++ b/twilio/rest/preview/wireless/command.py @@ -1,462 +1,595 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 CommandList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version): - """ - Initialize the CommandList +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") - :param Version version: Version that contains the resource + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CommandContext] = None - :returns: twilio.rest.preview.wireless.command.CommandList - :rtype: twilio.rest.preview.wireless.command.CommandList + @property + def _proxy(self) -> "CommandContext": """ - super(CommandList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Commands'.format(**self._solution) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def stream(self, device=values.unset, sim=values.unset, status=values.unset, - direction=values.unset, limit=None, page_size=None): + :returns: CommandContext for this 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 unicode device: The device - :param unicode sim: The sim - :param unicode status: The status - :param unicode direction: The direction - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + if self._context is None: + self._context = CommandContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.wireless.command.CommandInstance] + def fetch(self) -> "CommandInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the CommandInstance - page = self.page( - device=device, - sim=sim, - status=status, - direction=direction, - page_size=limits['page_size'], - ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched CommandInstance + """ + return self._proxy.fetch() - def list(self, device=values.unset, sim=values.unset, status=values.unset, - direction=values.unset, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the CommandInstance - :param unicode device: The device - :param unicode sim: The sim - :param unicode status: The status - :param unicode direction: The direction - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.wireless.command.CommandInstance] + :returns: The fetched CommandInstance """ - return list(self.stream( - device=device, - sim=sim, - status=status, - direction=direction, - limit=limit, - page_size=page_size, - )) + return await self._proxy.fetch_async() - def page(self, device=values.unset, sim=values.unset, status=values.unset, - direction=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def __repr__(self) -> str: """ - Retrieve a single page of CommandInstance records from the API. - Request is executed immediately + Provide a friendly representation - :param unicode device: The device - :param unicode sim: The sim - :param unicode status: The status - :param unicode direction: The direction - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: Page of CommandInstance - :rtype: twilio.rest.preview.wireless.command.CommandPage - """ - params = values.of({ - 'Device': device, - 'Sim': sim, - 'Status': status, - 'Direction': direction, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - response = self._version.page( - 'GET', - self._uri, - params=params, - ) +class CommandContext(InstanceContext): - return CommandPage(self._version, response, self._solution) + def __init__(self, version: Version, sid: str): + """ + Initialize the CommandContext - def get_page(self, target_url): + :param version: Version that contains the resource + :param sid: """ - Retrieve a specific page of CommandInstance records from the API. - Request is executed immediately + super().__init__(version) - :param str target_url: API-generated URL for the requested results page + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Commands/{sid}".format(**self._solution) - :returns: Page of CommandInstance - :rtype: twilio.rest.preview.wireless.command.CommandPage + def fetch(self) -> CommandInstance: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Fetch the CommandInstance - return CommandPage(self._version, response, self._solution) - def create(self, command, device=values.unset, sim=values.unset, - callback_method=values.unset, callback_url=values.unset, - command_mode=values.unset, include_sid=values.unset): + :returns: The fetched CommandInstance """ - Create a new CommandInstance - :param unicode command: The command - :param unicode device: The device - :param unicode sim: The sim - :param unicode callback_method: The callback_method - :param unicode callback_url: The callback_url - :param unicode command_mode: The command_mode - :param unicode include_sid: The include_sid + headers = values.of({}) - :returns: Newly created CommandInstance - :rtype: twilio.rest.preview.wireless.command.CommandInstance - """ - data = values.of({ - 'Command': command, - 'Device': device, - 'Sim': sim, - 'CallbackMethod': callback_method, - 'CallbackUrl': callback_url, - 'CommandMode': command_mode, - 'IncludeSid': include_sid, - }) + headers["Accept"] = "application/json" - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - return CommandInstance(self._version, payload, ) + return CommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def get(self, sid): + async def fetch_async(self) -> CommandInstance: """ - Constructs a CommandContext + Asynchronous coroutine to fetch the CommandInstance - :param sid: The sid - :returns: twilio.rest.preview.wireless.command.CommandContext - :rtype: twilio.rest.preview.wireless.command.CommandContext + :returns: The fetched CommandInstance """ - return CommandContext(self._version, sid=sid, ) - def __call__(self, sid): - """ - Constructs a CommandContext + headers = values.of({}) - :param sid: The sid + headers["Accept"] = "application/json" - :returns: twilio.rest.preview.wireless.command.CommandContext - :rtype: twilio.rest.preview.wireless.command.CommandContext - """ - return CommandContext(self._version, sid=sid, ) + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) class CommandPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - def __init__(self, version, response, solution): - """ - Initialize the CommandPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.preview.wireless.command.CommandPage - :rtype: twilio.rest.preview.wireless.command.CommandPage - """ - super(CommandPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): + def get_instance(self, payload: Dict[str, Any]) -> CommandInstance: """ Build an instance of CommandInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.wireless.command.CommandInstance - :rtype: twilio.rest.preview.wireless.command.CommandInstance + :param payload: Payload response from the API """ - return CommandInstance(self._version, payload, ) + return CommandInstance(self._version, payload) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class CommandContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ +class CommandList(ListResource): - def __init__(self, version, sid): + def __init__(self, version: Version): """ - Initialize the CommandContext + Initialize the CommandList - :param Version version: Version that contains the resource - :param sid: The sid + :param version: Version that contains the resource - :returns: twilio.rest.preview.wireless.command.CommandContext - :rtype: twilio.rest.preview.wireless.command.CommandContext """ - super(CommandContext, self).__init__(version) + super().__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Commands/{sid}'.format(**self._solution) + self._uri = "/Commands" - def fetch(self): + 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: """ - Fetch a CommandInstance + Create the CommandInstance - :returns: Fetched CommandInstance - :rtype: twilio.rest.preview.wireless.command.CommandInstance + :param command: + :param device: + :param sim: + :param callback_method: + :param callback_url: + :param command_mode: + :param include_sid: + + :returns: The created CommandInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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"}) - return CommandInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __repr__(self): - """ - Provide a friendly representation + headers["Accept"] = "application/json" - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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"}) -class CommandInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, sid=None): - """ - Initialize the CommandInstance - - :returns: twilio.rest.preview.wireless.command.CommandInstance - :rtype: twilio.rest.preview.wireless.command.CommandInstance - """ - super(CommandInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'device_sid': payload['device_sid'], - 'sim_sid': payload['sim_sid'], - 'command': payload['command'], - 'command_mode': payload['command_mode'], - 'status': payload['status'], - 'direction': payload['direction'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - } + headers["Content-Type"] = "application/x-www-form-urlencoded" - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + headers["Accept"] = "application/json" - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: CommandContext for this CommandInstance - :rtype: twilio.rest.preview.wireless.command.CommandContext - """ - if self._context is None: - self._context = CommandContext(self._version, sid=self._solution['sid'], ) - return self._context + return CommandInstance(self._version, payload) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + 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]: """ - return self._properties['sid'] + 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. - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + :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) - @property - def device_sid(self): - """ - :returns: The device_sid - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['device_sid'] + limits = self._version.read_limits(limit, page_size) + page = self.page( + device=device, + sim=sim, + status=status, + direction=direction, + page_size=limits["page_size"], + ) - @property - def sim_sid(self): - """ - :returns: The sim_sid - :rtype: unicode - """ - return self._properties['sim_sid'] + return self._version.stream(page, limits["limit"]) - @property - def command(self): - """ - :returns: The command - :rtype: unicode + 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]: """ - return self._properties['command'] + 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. - @property - def command_mode(self): - """ - :returns: The command_mode - :rtype: unicode + :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 """ - return self._properties['command_mode'] + 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"], + ) - @property - def status(self): + 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]: """ - :returns: The status - :rtype: unicode + 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: """ - return self._properties['status'] + Retrieve a single page of CommandInstance records from the API. + Request is executed immediately - @property - def direction(self): + :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 """ - :returns: The direction - :rtype: unicode + 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 """ - return self._properties['direction'] + data = values.of( + { + "Device": device, + "Sim": sim, + "Status": status, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def date_created(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The date_created - :rtype: datetime + 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 """ - return self._properties['date_created'] + response = self._version.domain.twilio.request("GET", target_url) + return CommandPage(self._version, response) - @property - def date_updated(self): + async def get_page_async(self, target_url: str) -> CommandPage: """ - :returns: The date_updated - :rtype: datetime + 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 """ - return self._properties['date_updated'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return CommandPage(self._version, response) - @property - def url(self): + def get(self, sid: str) -> CommandContext: """ - :returns: The url - :rtype: unicode + Constructs a CommandContext + + :param sid: """ - return self._properties['url'] + return CommandContext(self._version, sid=sid) - def fetch(self): + def __call__(self, sid: str) -> CommandContext: """ - Fetch a CommandInstance + Constructs a CommandContext - :returns: Fetched CommandInstance - :rtype: twilio.rest.preview.wireless.command.CommandInstance + :param sid: """ - return self._proxy.fetch() + return CommandContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/preview/wireless/rate_plan.py b/twilio/rest/preview/wireless/rate_plan.py index 53546410f5..95e45f1ef2 100644 --- a/twilio/rest/preview/wireless/rate_plan.py +++ b/twilio/rest/preview/wireless/rate_plan.py @@ -1,513 +1,699 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 RatePlanList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version): - """ - Initialize the RatePlanList +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") - :param Version version: Version that contains the resource + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[RatePlanContext] = None - :returns: twilio.rest.preview.wireless.rate_plan.RatePlanList - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanList + @property + def _proxy(self) -> "RatePlanContext": """ - super(RatePlanList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/RatePlans'.format(**self._solution) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def stream(self, limit=None, page_size=None): + :returns: RatePlanContext for this 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + if self._context is None: + self._context = RatePlanContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.wireless.rate_plan.RatePlanInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the RatePlanInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists RatePlanInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the RatePlanInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.wireless.rate_plan.RatePlanInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "RatePlanInstance": """ - Retrieve a single page of RatePlanInstance records from the API. - Request is executed immediately + Fetch the RatePlanInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of RatePlanInstance - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanPage + :returns: The fetched RatePlanInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return RatePlanPage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "RatePlanInstance": """ - Retrieve a specific page of RatePlanInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the RatePlanInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of RatePlanInstance - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanPage + :returns: The fetched RatePlanInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return RatePlanPage(self._version, response, self._solution) - - def create(self, unique_name=values.unset, friendly_name=values.unset, - data_enabled=values.unset, data_limit=values.unset, - data_metering=values.unset, messaging_enabled=values.unset, - voice_enabled=values.unset, commands_enabled=values.unset, - national_roaming_enabled=values.unset, - international_roaming=values.unset): - """ - Create a new RatePlanInstance - - :param unicode unique_name: The unique_name - :param unicode friendly_name: The friendly_name - :param bool data_enabled: The data_enabled - :param unicode data_limit: The data_limit - :param unicode data_metering: The data_metering - :param bool messaging_enabled: The messaging_enabled - :param bool voice_enabled: The voice_enabled - :param bool commands_enabled: The commands_enabled - :param bool national_roaming_enabled: The national_roaming_enabled - :param unicode international_roaming: The international_roaming - - :returns: Newly created RatePlanInstance - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanInstance - """ - data = values.of({ - 'UniqueName': unique_name, - 'FriendlyName': friendly_name, - 'DataEnabled': data_enabled, - 'DataLimit': data_limit, - 'DataMetering': data_metering, - 'MessagingEnabled': messaging_enabled, - 'VoiceEnabled': voice_enabled, - 'CommandsEnabled': commands_enabled, - 'NationalRoamingEnabled': national_roaming_enabled, - 'InternationalRoaming': serialize.map(international_roaming, lambda e: e), - }) + return await self._proxy.fetch_async() - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return RatePlanInstance(self._version, payload, ) - - def get(self, sid): + def update( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "RatePlanInstance": """ - Constructs a RatePlanContext + Update the RatePlanInstance - :param sid: The sid + :param unique_name: + :param friendly_name: - :returns: twilio.rest.preview.wireless.rate_plan.RatePlanContext - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanContext + :returns: The updated RatePlanInstance """ - return RatePlanContext(self._version, sid=sid, ) + return self._proxy.update( + unique_name=unique_name, + friendly_name=friendly_name, + ) - def __call__(self, sid): + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "RatePlanInstance": """ - Constructs a RatePlanContext + Asynchronous coroutine to update the RatePlanInstance - :param sid: The sid + :param unique_name: + :param friendly_name: - :returns: twilio.rest.preview.wireless.rate_plan.RatePlanContext - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanContext + :returns: The updated RatePlanInstance """ - return RatePlanContext(self._version, sid=sid, ) + return await self._proxy.update_async( + unique_name=unique_name, + friendly_name=friendly_name, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class RatePlanPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ +class RatePlanContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the RatePlanPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the RatePlanContext - :returns: twilio.rest.preview.wireless.rate_plan.RatePlanPage - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanPage + :param version: Version that contains the resource + :param sid: """ - super(RatePlanPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/RatePlans/{sid}".format(**self._solution) - def get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of RatePlanInstance + Deletes the RatePlanInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.preview.wireless.rate_plan.RatePlanInstance - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanInstance + :returns: True if delete succeeds, False otherwise """ - return RatePlanInstance(self._version, payload, ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the RatePlanInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class RatePlanContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, sid): + def fetch(self) -> RatePlanInstance: """ - Initialize the RatePlanContext + Fetch the RatePlanInstance - :param Version version: Version that contains the resource - :param sid: The sid - :returns: twilio.rest.preview.wireless.rate_plan.RatePlanContext - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanContext + :returns: The fetched RatePlanInstance """ - super(RatePlanContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/RatePlans/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RatePlanInstance: """ - Fetch a RatePlanInstance + Asynchronous coroutine to fetch the RatePlanInstance + - :returns: Fetched RatePlanInstance - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanInstance + :returns: The fetched RatePlanInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], ) + return RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def update(self, unique_name=values.unset, friendly_name=values.unset): + def update( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> RatePlanInstance: """ Update the RatePlanInstance - :param unicode unique_name: The unique_name - :param unicode friendly_name: The friendly_name + :param unique_name: + :param friendly_name: - :returns: Updated RatePlanInstance - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanInstance + :returns: The updated RatePlanInstance """ - data = values.of({'UniqueName': unique_name, 'FriendlyName': friendly_name, }) + + 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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) - return RatePlanInstance(self._version, payload, sid=self._solution['sid'], ) + return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) - def delete(self): + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> RatePlanInstance: """ - Deletes the RatePlanInstance + Asynchronous coroutine to update the RatePlanInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param unique_name: + :param friendly_name: + + :returns: The updated RatePlanInstance """ - return self._version.delete('delete', self._uri) - def __repr__(self): + 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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class RatePlanInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, sid=None): - """ - Initialize the RatePlanInstance - - :returns: twilio.rest.preview.wireless.rate_plan.RatePlanInstance - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanInstance - """ - super(RatePlanInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'unique_name': payload['unique_name'], - 'account_sid': payload['account_sid'], - 'friendly_name': payload['friendly_name'], - 'data_enabled': payload['data_enabled'], - 'data_metering': payload['data_metering'], - 'data_limit': deserialize.integer(payload['data_limit']), - 'messaging_enabled': payload['messaging_enabled'], - 'voice_enabled': payload['voice_enabled'], - 'national_roaming_enabled': payload['national_roaming_enabled'], - 'international_roaming': payload['international_roaming'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } +class RatePlanPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> RatePlanInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of RatePlanInstance - :returns: RatePlanContext for this RatePlanInstance - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = RatePlanContext(self._version, sid=self._solution['sid'], ) - return self._context + return RatePlanInstance(self._version, payload) - @property - def sid(self): + def __repr__(self) -> str: """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def unique_name(self): - """ - :returns: The unique_name - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['unique_name'] + return "" - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] +class RatePlanList(ListResource): - @property - def data_enabled(self): + def __init__(self, version: Version): """ - :returns: The data_enabled - :rtype: bool - """ - return self._properties['data_enabled'] + Initialize the RatePlanList - @property - def data_metering(self): - """ - :returns: The data_metering - :rtype: unicode - """ - return self._properties['data_metering'] + :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"}) - @property - def data_limit(self): - """ - :returns: The data_limit - :rtype: unicode - """ - return self._properties['data_limit'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def messaging_enabled(self): - """ - :returns: The messaging_enabled - :rtype: bool - """ - return self._properties['messaging_enabled'] + headers["Accept"] = "application/json" - @property - def voice_enabled(self): + 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]: """ - :returns: The voice_enabled - :rtype: bool + 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 """ - return self._properties['voice_enabled'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def national_roaming_enabled(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RatePlanInstance]: """ - :returns: The national_roaming_enabled - :rtype: bool + 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 """ - return self._properties['national_roaming_enabled'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def international_roaming(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RatePlanInstance]: """ - :returns: The international_roaming - :rtype: unicode + 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 self._properties['international_roaming'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def date_created(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RatePlanInstance]: """ - :returns: The date_created - :rtype: datetime + 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: """ - return self._properties['date_created'] + Retrieve a single page of RatePlanInstance records from the API. + Request is executed immediately - @property - def date_updated(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The date_updated - :rtype: datetime + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page of RatePlanInstance records from the API. + Request is executed immediately - @property - def url(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The url - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['url'] + Retrieve a specific page of RatePlanInstance records from the API. + Request is executed immediately - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of RatePlanInstance """ - Fetch a RatePlanInstance + response = self._version.domain.twilio.request("GET", target_url) + return RatePlanPage(self._version, response) - :returns: Fetched RatePlanInstance - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanInstance + async def get_page_async(self, target_url: str) -> RatePlanPage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of RatePlanInstance records from the API. + Request is executed immediately - def update(self, unique_name=values.unset, friendly_name=values.unset): + :param target_url: API-generated URL for the requested results page + + :returns: Page of RatePlanInstance """ - Update the RatePlanInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return RatePlanPage(self._version, response) - :param unicode unique_name: The unique_name - :param unicode friendly_name: The friendly_name + def get(self, sid: str) -> RatePlanContext: + """ + Constructs a RatePlanContext - :returns: Updated RatePlanInstance - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanInstance + :param sid: """ - return self._proxy.update(unique_name=unique_name, friendly_name=friendly_name, ) + return RatePlanContext(self._version, sid=sid) - def delete(self): + def __call__(self, sid: str) -> RatePlanContext: """ - Deletes the RatePlanInstance + Constructs a RatePlanContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: """ - return self._proxy.delete() + return RatePlanContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/preview/wireless/sim/__init__.py b/twilio/rest/preview/wireless/sim/__init__.py index b331ae7814..07a9e74da0 100644 --- a/twilio/rest/preview/wireless/sim/__init__.py +++ b/twilio/rest/preview/wireless/sim/__init__.py @@ -1,671 +1,833 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 SimList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version): - """ - Initialize the SimList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.preview.wireless.sim.SimList - :rtype: twilio.rest.preview.wireless.sim.SimList - """ - super(SimList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Sims'.format(**self._solution) - - def stream(self, status=values.unset, iccid=values.unset, - rate_plan=values.unset, e_id=values.unset, - sim_registration_code=values.unset, limit=None, page_size=None): - """ - 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 unicode status: The status - :param unicode iccid: The iccid - :param unicode rate_plan: The rate_plan - :param unicode e_id: The e_id - :param unicode sim_registration_code: The sim_registration_code - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.wireless.sim.SimInstance] - """ - 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'], +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") - return self._version.stream(page, limits['limit'], limits['page_limit']) + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[SimContext] = None - def list(self, status=values.unset, iccid=values.unset, rate_plan=values.unset, - e_id=values.unset, sim_registration_code=values.unset, limit=None, - page_size=None): + @property + def _proxy(self) -> "SimContext": """ - 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 unicode status: The status - :param unicode iccid: The iccid - :param unicode rate_plan: The rate_plan - :param unicode e_id: The e_id - :param unicode sim_registration_code: The sim_registration_code - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.wireless.sim.SimInstance] + :returns: SimContext for this SimInstance """ - 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, - )) + if self._context is None: + self._context = SimContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def page(self, status=values.unset, iccid=values.unset, rate_plan=values.unset, - e_id=values.unset, sim_registration_code=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "SimInstance": """ - Retrieve a single page of SimInstance records from the API. - Request is executed immediately - - :param unicode status: The status - :param unicode iccid: The iccid - :param unicode rate_plan: The rate_plan - :param unicode e_id: The e_id - :param unicode sim_registration_code: The sim_registration_code - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + Fetch the SimInstance - :returns: Page of SimInstance - :rtype: twilio.rest.preview.wireless.sim.SimPage - """ - params = 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, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - return SimPage(self._version, response, self._solution) - - def get_page(self, target_url): + :returns: The fetched SimInstance """ - Retrieve a specific page of SimInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page + return self._proxy.fetch() - :returns: Page of SimInstance - :rtype: twilio.rest.preview.wireless.sim.SimPage + async def fetch_async(self) -> "SimInstance": """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Asynchronous coroutine to fetch the SimInstance - return SimPage(self._version, response, self._solution) - def get(self, sid): + :returns: The fetched SimInstance """ - Constructs a SimContext - - :param sid: The sid + return await self._proxy.fetch_async() - :returns: twilio.rest.preview.wireless.sim.SimContext - :rtype: twilio.rest.preview.wireless.sim.SimContext + 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": """ - return SimContext(self._version, sid=sid, ) + Update the SimInstance - def __call__(self, sid): + :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 """ - Constructs a SimContext + 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, + ) - :param sid: The 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 + """ + 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, + ) - :returns: twilio.rest.preview.wireless.sim.SimContext - :rtype: twilio.rest.preview.wireless.sim.SimContext + @property + def usage(self) -> UsageList: + """ + Access the usage """ - return SimContext(self._version, sid=sid, ) + return self._proxy.usage - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class SimPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ +class SimContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the SimPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the SimContext - :returns: twilio.rest.preview.wireless.sim.SimPage - :rtype: twilio.rest.preview.wireless.sim.SimPage + :param version: Version that contains the resource + :param sid: """ - super(SimPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of SimInstance + self._solution = { + "sid": sid, + } + self._uri = "/Sims/{sid}".format(**self._solution) - :param dict payload: Payload response from the API + self._usage: Optional[UsageList] = None - :returns: twilio.rest.preview.wireless.sim.SimInstance - :rtype: twilio.rest.preview.wireless.sim.SimInstance + def fetch(self) -> SimInstance: """ - return SimInstance(self._version, payload, ) + Fetch the SimInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: The fetched SimInstance """ - return '' + headers = values.of({}) -class SimContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ + headers["Accept"] = "application/json" - def __init__(self, version, sid): - """ - Initialize the SimContext + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :param Version version: Version that contains the resource - :param sid: The sid + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - :returns: twilio.rest.preview.wireless.sim.SimContext - :rtype: twilio.rest.preview.wireless.sim.SimContext + async def fetch_async(self) -> SimInstance: """ - super(SimContext, self).__init__(version) + Asynchronous coroutine to fetch the SimInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Sims/{sid}'.format(**self._solution) - # Dependents - self._usage = None - - def fetch(self): + :returns: The fetched SimInstance """ - Fetch a SimInstance - :returns: Fetched SimInstance - :rtype: twilio.rest.preview.wireless.sim.SimInstance - """ - params = values.of({}) + headers = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], ) + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def update(self, unique_name=values.unset, callback_method=values.unset, - callback_url=values.unset, friendly_name=values.unset, - rate_plan=values.unset, status=values.unset, - commands_callback_method=values.unset, - commands_callback_url=values.unset, sms_fallback_method=values.unset, - sms_fallback_url=values.unset, sms_method=values.unset, - sms_url=values.unset, voice_fallback_method=values.unset, - voice_fallback_url=values.unset, voice_method=values.unset, - voice_url=values.unset): + 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 unicode unique_name: The unique_name - :param unicode callback_method: The callback_method - :param unicode callback_url: The callback_url - :param unicode friendly_name: The friendly_name - :param unicode rate_plan: The rate_plan - :param unicode status: The status - :param unicode commands_callback_method: The commands_callback_method - :param unicode commands_callback_url: The commands_callback_url - :param unicode sms_fallback_method: The sms_fallback_method - :param unicode sms_fallback_url: The sms_fallback_url - :param unicode sms_method: The sms_method - :param unicode sms_url: The sms_url - :param unicode voice_fallback_method: The voice_fallback_method - :param unicode voice_fallback_url: The voice_fallback_url - :param unicode voice_method: The voice_method - :param unicode voice_url: The voice_url - - :returns: Updated SimInstance - :rtype: twilio.rest.preview.wireless.sim.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, - }) + :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( - 'POST', - self._uri, - data=data, + 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'], ) + return SimInstance(self._version, payload, sid=self._solution["sid"]) @property - def usage(self): + def usage(self) -> UsageList: """ Access the usage - - :returns: twilio.rest.preview.wireless.sim.usage.UsageList - :rtype: twilio.rest.preview.wireless.sim.usage.UsageList """ if self._usage is None: - self._usage = UsageList(self._version, sim_sid=self._solution['sid'], ) + self._usage = UsageList( + self._version, + self._solution["sid"], + ) return self._usage - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class SimInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, sid=None): - """ - Initialize the SimInstance - - :returns: twilio.rest.preview.wireless.sim.SimInstance - :rtype: twilio.rest.preview.wireless.sim.SimInstance - """ - super(SimInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'unique_name': payload['unique_name'], - 'account_sid': payload['account_sid'], - 'rate_plan_sid': payload['rate_plan_sid'], - 'friendly_name': payload['friendly_name'], - 'iccid': payload['iccid'], - 'e_id': payload['e_id'], - 'status': payload['status'], - 'commands_callback_url': payload['commands_callback_url'], - 'commands_callback_method': payload['commands_callback_method'], - 'sms_fallback_method': payload['sms_fallback_method'], - 'sms_fallback_url': payload['sms_fallback_url'], - 'sms_method': payload['sms_method'], - 'sms_url': payload['sms_url'], - 'voice_fallback_method': payload['voice_fallback_method'], - 'voice_fallback_url': payload['voice_fallback_url'], - 'voice_method': payload['voice_method'], - 'voice_url': payload['voice_url'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - 'links': payload['links'], - } - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } +class SimPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> SimInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of SimInstance - :returns: SimContext for this SimInstance - :rtype: twilio.rest.preview.wireless.sim.SimContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = SimContext(self._version, sid=self._solution['sid'], ) - return self._context + return SimInstance(self._version, payload) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['sid'] + Provide a friendly representation - @property - def unique_name(self): - """ - :returns: The unique_name - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['unique_name'] + return "" - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def rate_plan_sid(self): - """ - :returns: The rate_plan_sid - :rtype: unicode - """ - return self._properties['rate_plan_sid'] +class SimList(ListResource): - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode + def __init__(self, version: Version): """ - return self._properties['friendly_name'] + Initialize the SimList - @property - def iccid(self): - """ - :returns: The iccid - :rtype: unicode - """ - return self._properties['iccid'] + :param version: Version that contains the resource - @property - def e_id(self): """ - :returns: The e_id - :rtype: unicode - """ - return self._properties['e_id'] + super().__init__(version) - @property - def status(self): - """ - :returns: The status - :rtype: unicode - """ - return self._properties['status'] + self._uri = "/Sims" - @property - def commands_callback_url(self): - """ - :returns: The commands_callback_url - :rtype: unicode + 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]: """ - return self._properties['commands_callback_url'] + 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. - @property - def commands_callback_method(self): - """ - :returns: The commands_callback_method - :rtype: unicode - """ - return self._properties['commands_callback_method'] + :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) - @property - def sms_fallback_method(self): - """ - :returns: The sms_fallback_method - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['sms_fallback_method'] + 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"], + ) - @property - def sms_fallback_url(self): - """ - :returns: The sms_fallback_url - :rtype: unicode - """ - return self._properties['sms_fallback_url'] + return self._version.stream(page, limits["limit"]) - @property - def sms_method(self): - """ - :returns: The sms_method - :rtype: unicode + 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]: """ - return self._properties['sms_method'] + 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. - @property - def sms_url(self): - """ - :returns: The sms_url - :rtype: unicode - """ - return self._properties['sms_url'] + :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) - @property - def voice_fallback_method(self): - """ - :returns: The voice_fallback_method - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['voice_fallback_method'] + 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"], + ) - @property - def voice_fallback_url(self): - """ - :returns: The voice_fallback_url - :rtype: unicode - """ - return self._properties['voice_fallback_url'] + return self._version.stream_async(page, limits["limit"]) - @property - def voice_method(self): - """ - :returns: The voice_method - :rtype: unicode + 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]: """ - return self._properties['voice_method'] + Lists SimInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def voice_url(self): - """ - :returns: The voice_url - :rtype: unicode - """ - return self._properties['voice_url'] + :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, + ) + ) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + 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. - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime + :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: """ - return self._properties['date_updated'] + Retrieve a single page of SimInstance records from the API. + Request is executed immediately - @property - def url(self): + :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 """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + 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, + } + ) - @property - def links(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The links - :rtype: unicode + 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 """ - return self._properties['links'] + response = self._version.domain.twilio.request("GET", target_url) + return SimPage(self._version, response) - def fetch(self): + async def get_page_async(self, target_url: str) -> SimPage: """ - Fetch a SimInstance + 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: Fetched SimInstance - :rtype: twilio.rest.preview.wireless.sim.SimInstance + :returns: Page of SimInstance """ - return self._proxy.fetch() + response = await self._version.domain.twilio.request_async("GET", target_url) + return SimPage(self._version, response) - def update(self, unique_name=values.unset, callback_method=values.unset, - callback_url=values.unset, friendly_name=values.unset, - rate_plan=values.unset, status=values.unset, - commands_callback_method=values.unset, - commands_callback_url=values.unset, sms_fallback_method=values.unset, - sms_fallback_url=values.unset, sms_method=values.unset, - sms_url=values.unset, voice_fallback_method=values.unset, - voice_fallback_url=values.unset, voice_method=values.unset, - voice_url=values.unset): + def get(self, sid: str) -> SimContext: """ - Update the SimInstance + Constructs a SimContext - :param unicode unique_name: The unique_name - :param unicode callback_method: The callback_method - :param unicode callback_url: The callback_url - :param unicode friendly_name: The friendly_name - :param unicode rate_plan: The rate_plan - :param unicode status: The status - :param unicode commands_callback_method: The commands_callback_method - :param unicode commands_callback_url: The commands_callback_url - :param unicode sms_fallback_method: The sms_fallback_method - :param unicode sms_fallback_url: The sms_fallback_url - :param unicode sms_method: The sms_method - :param unicode sms_url: The sms_url - :param unicode voice_fallback_method: The voice_fallback_method - :param unicode voice_fallback_url: The voice_fallback_url - :param unicode voice_method: The voice_method - :param unicode voice_url: The voice_url - - :returns: Updated SimInstance - :rtype: twilio.rest.preview.wireless.sim.SimInstance + :param sid: """ - 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, - ) + return SimContext(self._version, sid=sid) - @property - def usage(self): + def __call__(self, sid: str) -> SimContext: """ - Access the usage + Constructs a SimContext - :returns: twilio.rest.preview.wireless.sim.usage.UsageList - :rtype: twilio.rest.preview.wireless.sim.usage.UsageList + :param sid: """ - return self._proxy.usage + return SimContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/preview/wireless/sim/usage.py b/twilio/rest/preview/wireless/sim/usage.py index 13642a6d38..aff3731b51 100644 --- a/twilio/rest/preview/wireless/sim/usage.py +++ b/twilio/rest/preview/wireless/sim/usage.py @@ -1,294 +1,249 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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.page import Page +from twilio.base.version import Version -class UsageList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ +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 - def __init__(self, version, sim_sid): + @property + def _proxy(self) -> "UsageContext": """ - Initialize the UsageList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param sim_sid: The sim_sid + :returns: UsageContext for this UsageInstance + """ + if self._context is None: + self._context = UsageContext( + self._version, + sim_sid=self._solution["sim_sid"], + ) + return self._context - :returns: twilio.rest.preview.wireless.sim.usage.UsageList - :rtype: twilio.rest.preview.wireless.sim.usage.UsageList + def fetch( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> "UsageInstance": """ - super(UsageList, self).__init__(version) + Fetch the UsageInstance - # Path Solution - self._solution = {'sim_sid': sim_sid, } + :param end: + :param start: - def get(self): + :returns: The fetched UsageInstance """ - Constructs a UsageContext + return self._proxy.fetch( + end=end, + start=start, + ) - :returns: twilio.rest.preview.wireless.sim.usage.UsageContext - :rtype: twilio.rest.preview.wireless.sim.usage.UsageContext + async def fetch_async( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> "UsageInstance": """ - return UsageContext(self._version, sim_sid=self._solution['sim_sid'], ) + Asynchronous coroutine to fetch the UsageInstance - def __call__(self): - """ - Constructs a UsageContext + :param end: + :param start: - :returns: twilio.rest.preview.wireless.sim.usage.UsageContext - :rtype: twilio.rest.preview.wireless.sim.usage.UsageContext + :returns: The fetched UsageInstance """ - return UsageContext(self._version, sim_sid=self._solution['sim_sid'], ) + return await self._proxy.fetch_async( + end=end, + start=start, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class UsagePage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ +class UsageContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sim_sid: str): """ - Initialize the UsagePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param sim_sid: The sim_sid + Initialize the UsageContext - :returns: twilio.rest.preview.wireless.sim.usage.UsagePage - :rtype: twilio.rest.preview.wireless.sim.usage.UsagePage + :param version: Version that contains the resource + :param sim_sid: """ - super(UsagePage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sim_sid": sim_sid, + } + self._uri = "/Sims/{sim_sid}/Usage".format(**self._solution) - def get_instance(self, payload): + def fetch( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> UsageInstance: """ - Build an instance of UsageInstance - - :param dict payload: Payload response from the API + Fetch the UsageInstance - :returns: twilio.rest.preview.wireless.sim.usage.UsageInstance - :rtype: twilio.rest.preview.wireless.sim.usage.UsageInstance - """ - return UsageInstance(self._version, payload, sim_sid=self._solution['sim_sid'], ) + :param end: + :param start: - def __repr__(self): + :returns: The fetched UsageInstance """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str - """ - return '' + data = values.of( + { + "End": end, + "Start": start, + } + ) + headers = values.of({}) -class UsageContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ + headers["Accept"] = "application/json" - def __init__(self, version, sim_sid): - """ - Initialize the UsageContext + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) - :param Version version: Version that contains the resource - :param sim_sid: The sim_sid + return UsageInstance( + self._version, + payload, + sim_sid=self._solution["sim_sid"], + ) - :returns: twilio.rest.preview.wireless.sim.usage.UsageContext - :rtype: twilio.rest.preview.wireless.sim.usage.UsageContext + async def fetch_async( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> UsageInstance: """ - super(UsageContext, self).__init__(version) + Asynchronous coroutine to fetch the UsageInstance - # Path Solution - self._solution = {'sim_sid': sim_sid, } - self._uri = '/Sims/{sim_sid}/Usage'.format(**self._solution) + :param end: + :param start: - def fetch(self, end=values.unset, start=values.unset): + :returns: The fetched UsageInstance """ - Fetch a UsageInstance - :param unicode end: The end - :param unicode start: The start + data = values.of( + { + "End": end, + "Start": start, + } + ) - :returns: Fetched UsageInstance - :rtype: twilio.rest.preview.wireless.sim.usage.UsageInstance - """ - params = values.of({'End': end, 'Start': start, }) + headers = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], ) + return UsageInstance( + self._version, + payload, + sim_sid=self._solution["sim_sid"], + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class UsageInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, payload, sim_sid): """ - Initialize the UsageInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: twilio.rest.preview.wireless.sim.usage.UsageInstance - :rtype: twilio.rest.preview.wireless.sim.usage.UsageInstance - """ - super(UsageInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sim_sid': payload['sim_sid'], - 'sim_unique_name': payload['sim_unique_name'], - 'account_sid': payload['account_sid'], - 'period': payload['period'], - 'commands_usage': payload['commands_usage'], - 'commands_costs': payload['commands_costs'], - 'data_usage': payload['data_usage'], - 'data_costs': payload['data_costs'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = {'sim_sid': sim_sid, } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.preview.wireless.sim.usage.UsageContext - """ - if self._context is None: - self._context = UsageContext(self._version, sim_sid=self._solution['sim_sid'], ) - return self._context - - @property - def sim_sid(self): - """ - :returns: The sim_sid - :rtype: unicode - """ - return self._properties['sim_sid'] - @property - def sim_unique_name(self): - """ - :returns: The sim_unique_name - :rtype: unicode - """ - return self._properties['sim_unique_name'] - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] +class UsageList(ListResource): - @property - def period(self): + def __init__(self, version: Version, sim_sid: str): """ - :returns: The period - :rtype: dict - """ - return self._properties['period'] + Initialize the UsageList - @property - def commands_usage(self): - """ - :returns: The commands_usage - :rtype: dict - """ - return self._properties['commands_usage'] + :param version: Version that contains the resource + :param sim_sid: - @property - def commands_costs(self): """ - :returns: The commands_costs - :rtype: dict - """ - return self._properties['commands_costs'] + super().__init__(version) - @property - def data_usage(self): - """ - :returns: The data_usage - :rtype: dict - """ - return self._properties['data_usage'] + # Path Solution + self._solution = { + "sim_sid": sim_sid, + } - @property - def data_costs(self): - """ - :returns: The data_costs - :rtype: dict + def get(self) -> UsageContext: """ - return self._properties['data_costs'] + Constructs a UsageContext - @property - def url(self): - """ - :returns: The url - :rtype: unicode """ - return self._properties['url'] + return UsageContext(self._version, sim_sid=self._solution["sim_sid"]) - def fetch(self, end=values.unset, start=values.unset): + def __call__(self) -> UsageContext: """ - Fetch a UsageInstance - - :param unicode end: The end - :param unicode start: The start + Constructs a UsageContext - :returns: Fetched UsageInstance - :rtype: twilio.rest.preview.wireless.sim.usage.UsageInstance """ - return self._proxy.fetch(end=end, start=start, ) + return UsageContext(self._version, sim_sid=self._solution["sim_sid"]) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 "" 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 "" 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 "" + + +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 "" 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 "" + + +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 "" 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 "" 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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "" diff --git a/twilio/rest/pricing/__init__.py b/twilio/rest/pricing/__init__.py index 66d6b92a40..91da8751d9 100644 --- a/twilio/rest/pricing/__init__.py +++ b/twilio/rest/pricing/__init__.py @@ -1,67 +1,55 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" +from warnings import warn -from twilio.base.domain import Domain -from twilio.rest.pricing.v1 import V1 +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(Domain): - - def __init__(self, twilio): - """ - Initialize the Pricing Domain - - :returns: Domain for Pricing - :rtype: twilio.rest.pricing.Pricing - """ - super(Pricing, self).__init__(twilio) - - self.base_url = 'https://pricing.twilio.com' - - # Versions - self._v1 = None - +class Pricing(PricingBase): @property - def v1(self): - """ - :returns: Version v1 of pricing - :rtype: twilio.rest.pricing.v1.V1 - """ - if self._v1 is None: - self._v1 = V1(self) - return self._v1 - - @property - def messaging(self): - """ - :rtype: twilio.rest.pricing.v1.messaging.MessagingList - """ + def messaging(self) -> MessagingList: + warn( + "messaging is deprecated. Use v1.messaging instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v1.messaging @property - def phone_numbers(self): - """ - :rtype: twilio.rest.pricing.v1.phone_number.PhoneNumberList - """ + 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): - """ - :rtype: twilio.rest.pricing.v1.voice.VoiceList - """ - return self.v1.voice + def voice(self) -> VoiceList: + warn( + "voice is deprecated. Use v2.voice instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.voice - def __repr__(self): - """ - Provide a friendly representation + @property + def countries(self) -> CountryList: + warn( + "countries is deprecated. Use v2.countries instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.countries - :returns: Machine friendly representation - :rtype: str - """ - return '' + @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 index bdc8d5ba80..ba8b65885d 100644 --- a/twilio/rest/pricing/v1/__init__.py +++ b/twilio/rest/pricing/v1/__init__.py @@ -1,12 +1,20 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 @@ -14,51 +22,38 @@ class V1(Version): - def __init__(self, domain): + def __init__(self, domain: Domain): """ Initialize the V1 version of Pricing - :returns: V1 version of Pricing - :rtype: twilio.rest.pricing.v1.V1.V1 + :param domain: The Twilio.pricing domain """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._messaging = None - self._phone_numbers = None - self._voice = None + super().__init__(domain, "v1") + self._messaging: Optional[MessagingList] = None + self._phone_numbers: Optional[PhoneNumberList] = None + self._voice: Optional[VoiceList] = None @property - def messaging(self): - """ - :rtype: twilio.rest.pricing.v1.messaging.MessagingList - """ + def messaging(self) -> MessagingList: if self._messaging is None: self._messaging = MessagingList(self) return self._messaging @property - def phone_numbers(self): - """ - :rtype: twilio.rest.pricing.v1.phone_number.PhoneNumberList - """ + def phone_numbers(self) -> PhoneNumberList: if self._phone_numbers is None: self._phone_numbers = PhoneNumberList(self) return self._phone_numbers @property - def voice(self): - """ - :rtype: twilio.rest.pricing.v1.voice.VoiceList - """ + def voice(self) -> VoiceList: if self._voice is None: self._voice = VoiceList(self) return self._voice - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/pricing/v1/messaging/__init__.py b/twilio/rest/pricing/v1/messaging/__init__.py index 7391aaa826..df5c148b81 100644 --- a/twilio/rest/pricing/v1/messaging/__init__.py +++ b/twilio/rest/pricing/v1/messaging/__init__.py @@ -1,146 +1,54 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base.instance_resource import InstanceResource +from typing import Optional + + from twilio.base.list_resource import ListResource -from twilio.base.page import Page +from twilio.base.version import Version + from twilio.rest.pricing.v1.messaging.country import CountryList class MessagingList(ListResource): - """ """ - def __init__(self, version): + def __init__(self, version: Version): """ Initialize the MessagingList - :param Version version: Version that contains the resource + :param version: Version that contains the resource - :returns: twilio.rest.pricing.v1.messaging.MessagingList - :rtype: twilio.rest.pricing.v1.messaging.MessagingList """ - super(MessagingList, self).__init__(version) + super().__init__(version) - # Path Solution - self._solution = {} + self._uri = "/Messaging" - # Components - self._countries = None + self._countries: Optional[CountryList] = None @property - def countries(self): + def countries(self) -> CountryList: """ Access the countries - - :returns: twilio.rest.pricing.v1.messaging.country.CountryList - :rtype: twilio.rest.pricing.v1.messaging.country.CountryList """ if self._countries is None: - self._countries = CountryList(self._version, ) + self._countries = CountryList(self._version) return self._countries - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class MessagingPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the MessagingPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.pricing.v1.messaging.MessagingPage - :rtype: twilio.rest.pricing.v1.messaging.MessagingPage - """ - super(MessagingPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of MessagingInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.pricing.v1.messaging.MessagingInstance - :rtype: twilio.rest.pricing.v1.messaging.MessagingInstance - """ - return MessagingInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class MessagingInstance(InstanceResource): - """ """ - - def __init__(self, version, payload): - """ - Initialize the MessagingInstance - - :returns: twilio.rest.pricing.v1.messaging.MessagingInstance - :rtype: twilio.rest.pricing.v1.messaging.MessagingInstance - """ - super(MessagingInstance, self).__init__(version) - - # Marshaled Properties - self._properties = {'name': payload['name'], 'url': payload['url'], 'links': payload['links'], } - - # Context - self._context = None - self._solution = {} - - @property - def name(self): - """ - :returns: The name - :rtype: unicode - """ - return self._properties['name'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def links(self): - """ - :returns: The links - :rtype: unicode - """ - return self._properties['links'] - - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/pricing/v1/messaging/country.py b/twilio/rest/pricing/v1/messaging/country.py index d2e9ab7bbd..49360cd85c 100644 --- a/twilio/rest/pricing/v1/messaging/country.py +++ b/twilio/rest/pricing/v1/messaging/country.py @@ -1,337 +1,415 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 CountryList(ListResource): - """ """ - - def __init__(self, version): - """ - Initialize the CountryList +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") - :param Version version: Version that contains the resource + self._solution = { + "iso_country": iso_country or self.iso_country, + } + self._context: Optional[CountryContext] = None - :returns: twilio.rest.pricing.v1.messaging.country.CountryList - :rtype: twilio.rest.pricing.v1.messaging.country.CountryList + @property + def _proxy(self) -> "CountryContext": """ - super(CountryList, self).__init__(version) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - # Path Solution - self._solution = {} - self._uri = '/Messaging/Countries'.format(**self._solution) + :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 stream(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the CountryInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.pricing.v1.messaging.country.CountryInstance] + :returns: The fetched CountryInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(page_size=limits['page_size'], ) + async def fetch_async(self) -> "CountryInstance": + """ + Asynchronous coroutine to fetch the CountryInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + return await self._proxy.fetch_async() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.pricing.v1.messaging.country.CountryInstance] + def __repr__(self) -> str: """ - return list(self.stream(limit=limit, page_size=page_size, )) + Provide a friendly representation - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + :returns: Machine friendly representation """ - Retrieve a single page of CountryInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of CountryInstance - :rtype: twilio.rest.pricing.v1.messaging.country.CountryPage +class CountryContext(InstanceContext): + + def __init__(self, version: Version, iso_country: str): """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the CountryContext - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + :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) - return CountryPage(self._version, response, self._solution) + # Path Solution + self._solution = { + "iso_country": iso_country, + } + self._uri = "/Messaging/Countries/{iso_country}".format(**self._solution) - def get_page(self, target_url): + def fetch(self) -> CountryInstance: """ - Retrieve a specific page of CountryInstance records from the API. - Request is executed immediately + Fetch the CountryInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of CountryInstance - :rtype: twilio.rest.pricing.v1.messaging.country.CountryPage + :returns: The fetched CountryInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return CountryPage(self._version, response, self._solution) + headers = values.of({}) - def get(self, iso_country): - """ - Constructs a CountryContext + headers["Accept"] = "application/json" - :param iso_country: The iso_country + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.pricing.v1.messaging.country.CountryContext - :rtype: twilio.rest.pricing.v1.messaging.country.CountryContext - """ - return CountryContext(self._version, iso_country=iso_country, ) + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) - def __call__(self, iso_country): + async def fetch_async(self) -> CountryInstance: """ - Constructs a CountryContext + Asynchronous coroutine to fetch the CountryInstance - :param iso_country: The iso_country - :returns: twilio.rest.pricing.v1.messaging.country.CountryContext - :rtype: twilio.rest.pricing.v1.messaging.country.CountryContext + :returns: The fetched CountryInstance """ - return CountryContext(self._version, iso_country=iso_country, ) - def __repr__(self): + 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 - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) class CountryPage(Page): - """ """ - def __init__(self, version, response, solution): + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: """ - Initialize the CountryPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Build an instance of CountryInstance - :returns: twilio.rest.pricing.v1.messaging.country.CountryPage - :rtype: twilio.rest.pricing.v1.messaging.country.CountryPage + :param payload: Payload response from the API """ - super(CountryPage, self).__init__(version, response) + return CountryInstance(self._version, payload) - # Path Solution - self._solution = solution + def __repr__(self) -> str: + """ + Provide a friendly representation - def get_instance(self, payload): + :returns: Machine friendly representation """ - Build an instance of CountryInstance + return "" - :param dict payload: Payload response from the API - :returns: twilio.rest.pricing.v1.messaging.country.CountryInstance - :rtype: twilio.rest.pricing.v1.messaging.country.CountryInstance - """ - return CountryInstance(self._version, payload, ) +class CountryList(ListResource): - def __repr__(self): + def __init__(self, version: Version): """ - Provide a friendly representation + Initialize the CountryList + + :param version: Version that contains the resource - :returns: Machine friendly representation - :rtype: str """ - return '' + super().__init__(version) + self._uri = "/Messaging/Countries" -class CountryContext(InstanceContext): - """ """ + 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. - def __init__(self, version, iso_country): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - Initialize the CountryContext + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - :param Version version: Version that contains the resource - :param iso_country: The iso_country + return self._version.stream(page, limits["limit"]) - :returns: twilio.rest.pricing.v1.messaging.country.CountryContext - :rtype: twilio.rest.pricing.v1.messaging.country.CountryContext + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CountryInstance]: """ - super(CountryContext, self).__init__(version) + 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. - # Path Solution - self._solution = {'iso_country': iso_country, } - self._uri = '/Messaging/Countries/{iso_country}'.format(**self._solution) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - def fetch(self): + :returns: Generator that will yield up to limit results """ - Fetch a CountryInstance + 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"]) - :returns: Fetched CountryInstance - :rtype: twilio.rest.pricing.v1.messaging.country.CountryInstance + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: """ - params = values.of({}) + 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) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) ) - return CountryInstance(self._version, payload, iso_country=self._solution['iso_country'], ) + 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. - def __repr__(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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: """ - Provide a friendly representation + Retrieve a single page of CountryInstance records from the API. + Request is executed immediately - :returns: Machine friendly representation - :rtype: str + :param page_token: PageToken provided by the API + :param page_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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) -class CountryInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) - def __init__(self, version, payload, iso_country=None): + 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: """ - Initialize the CountryInstance + 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: twilio.rest.pricing.v1.messaging.country.CountryInstance - :rtype: twilio.rest.pricing.v1.messaging.country.CountryInstance + :returns: Page of CountryInstance """ - super(CountryInstance, self).__init__(version) + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - # Marshaled Properties - self._properties = { - 'country': payload['country'], - 'iso_country': payload['iso_country'], - 'url': payload['url'], - 'outbound_sms_prices': payload.get('outbound_sms_prices'), - 'inbound_sms_prices': payload.get('inbound_sms_prices'), - 'price_unit': payload.get('price_unit'), - } + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - # Context - self._context = None - self._solution = {'iso_country': iso_country or self._properties['iso_country'], } + headers["Accept"] = "application/json" - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) - :returns: CountryContext for this CountryInstance - :rtype: twilio.rest.pricing.v1.messaging.country.CountryContext + def get_page(self, target_url: str) -> CountryPage: """ - if self._context is None: - self._context = CountryContext(self._version, iso_country=self._solution['iso_country'], ) - return self._context + Retrieve a specific page of CountryInstance records from the API. + Request is executed immediately - @property - def country(self): - """ - :returns: The country - :rtype: unicode - """ - return self._properties['country'] + :param target_url: API-generated URL for the requested results page - @property - def iso_country(self): - """ - :returns: The iso_country - :rtype: unicode + :returns: Page of CountryInstance """ - return self._properties['iso_country'] + response = self._version.domain.twilio.request("GET", target_url) + return CountryPage(self._version, response) - @property - def outbound_sms_prices(self): - """ - :returns: The outbound_sms_prices - :rtype: unicode + async def get_page_async(self, target_url: str) -> CountryPage: """ - return self._properties['outbound_sms_prices'] + Asynchronously retrieve a specific page of CountryInstance records from the API. + Request is executed immediately - @property - def inbound_sms_prices(self): - """ - :returns: The inbound_sms_prices - :rtype: unicode - """ - return self._properties['inbound_sms_prices'] + :param target_url: API-generated URL for the requested results page - @property - def price_unit(self): - """ - :returns: The price_unit - :rtype: unicode + :returns: Page of CountryInstance """ - return self._properties['price_unit'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return CountryPage(self._version, response) - @property - def url(self): + def get(self, iso_country: str) -> CountryContext: """ - :returns: The url - :rtype: unicode + 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 self._properties['url'] + return CountryContext(self._version, iso_country=iso_country) - def fetch(self): + def __call__(self, iso_country: str) -> CountryContext: """ - Fetch a CountryInstance + Constructs a CountryContext - :returns: Fetched CountryInstance - :rtype: twilio.rest.pricing.v1.messaging.country.CountryInstance + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. """ - return self._proxy.fetch() + return CountryContext(self._version, iso_country=iso_country) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/pricing/v1/phone_number/__init__.py b/twilio/rest/pricing/v1/phone_number/__init__.py index 833e6a1ec7..429ce9b14c 100644 --- a/twilio/rest/pricing/v1/phone_number/__init__.py +++ b/twilio/rest/pricing/v1/phone_number/__init__.py @@ -1,146 +1,54 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base.instance_resource import InstanceResource +from typing import Optional + + from twilio.base.list_resource import ListResource -from twilio.base.page import Page +from twilio.base.version import Version + from twilio.rest.pricing.v1.phone_number.country import CountryList class PhoneNumberList(ListResource): - """ """ - def __init__(self, version): + def __init__(self, version: Version): """ Initialize the PhoneNumberList - :param Version version: Version that contains the resource + :param version: Version that contains the resource - :returns: twilio.rest.pricing.v1.phone_number.PhoneNumberList - :rtype: twilio.rest.pricing.v1.phone_number.PhoneNumberList """ - super(PhoneNumberList, self).__init__(version) + super().__init__(version) - # Path Solution - self._solution = {} + self._uri = "/PhoneNumbers" - # Components - self._countries = None + self._countries: Optional[CountryList] = None @property - def countries(self): + def countries(self) -> CountryList: """ Access the countries - - :returns: twilio.rest.pricing.v1.phone_number.country.CountryList - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryList """ if self._countries is None: - self._countries = CountryList(self._version, ) + self._countries = CountryList(self._version) return self._countries - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class PhoneNumberPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the PhoneNumberPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.pricing.v1.phone_number.PhoneNumberPage - :rtype: twilio.rest.pricing.v1.phone_number.PhoneNumberPage - """ - super(PhoneNumberPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of PhoneNumberInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.pricing.v1.phone_number.PhoneNumberInstance - :rtype: twilio.rest.pricing.v1.phone_number.PhoneNumberInstance - """ - return PhoneNumberInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class PhoneNumberInstance(InstanceResource): - """ """ - - def __init__(self, version, payload): - """ - Initialize the PhoneNumberInstance - - :returns: twilio.rest.pricing.v1.phone_number.PhoneNumberInstance - :rtype: twilio.rest.pricing.v1.phone_number.PhoneNumberInstance - """ - super(PhoneNumberInstance, self).__init__(version) - - # Marshaled Properties - self._properties = {'name': payload['name'], 'url': payload['url'], 'links': payload['links'], } - - # Context - self._context = None - self._solution = {} - - @property - def name(self): - """ - :returns: The name - :rtype: unicode - """ - return self._properties['name'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def links(self): - """ - :returns: The links - :rtype: unicode - """ - return self._properties['links'] - - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/pricing/v1/phone_number/country.py b/twilio/rest/pricing/v1/phone_number/country.py index 658a553d53..2d11cd1c3e 100644 --- a/twilio/rest/pricing/v1/phone_number/country.py +++ b/twilio/rest/pricing/v1/phone_number/country.py @@ -1,328 +1,413 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 CountryList(ListResource): - """ """ - - def __init__(self, version): - """ - Initialize the CountryList +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") - :param Version version: Version that contains the resource + self._solution = { + "iso_country": iso_country or self.iso_country, + } + self._context: Optional[CountryContext] = None - :returns: twilio.rest.pricing.v1.phone_number.country.CountryList - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryList + @property + def _proxy(self) -> "CountryContext": """ - super(CountryList, self).__init__(version) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - # Path Solution - self._solution = {} - self._uri = '/PhoneNumbers/Countries'.format(**self._solution) + :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 stream(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the CountryInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.pricing.v1.phone_number.country.CountryInstance] + :returns: The fetched CountryInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(page_size=limits['page_size'], ) + async def fetch_async(self) -> "CountryInstance": + """ + Asynchronous coroutine to fetch the CountryInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + return await self._proxy.fetch_async() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.pricing.v1.phone_number.country.CountryInstance] + def __repr__(self) -> str: """ - return list(self.stream(limit=limit, page_size=page_size, )) + Provide a friendly representation - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + :returns: Machine friendly representation """ - Retrieve a single page of CountryInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of CountryInstance - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryPage +class CountryContext(InstanceContext): + + def __init__(self, version: Version, iso_country: str): """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the CountryContext - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + :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) - return CountryPage(self._version, response, self._solution) + # Path Solution + self._solution = { + "iso_country": iso_country, + } + self._uri = "/PhoneNumbers/Countries/{iso_country}".format(**self._solution) - def get_page(self, target_url): + def fetch(self) -> CountryInstance: """ - Retrieve a specific page of CountryInstance records from the API. - Request is executed immediately + Fetch the CountryInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of CountryInstance - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryPage + :returns: The fetched CountryInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return CountryPage(self._version, response, self._solution) + headers = values.of({}) - def get(self, iso_country): - """ - Constructs a CountryContext + headers["Accept"] = "application/json" - :param iso_country: The iso_country + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.pricing.v1.phone_number.country.CountryContext - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryContext - """ - return CountryContext(self._version, iso_country=iso_country, ) + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) - def __call__(self, iso_country): + async def fetch_async(self) -> CountryInstance: """ - Constructs a CountryContext + Asynchronous coroutine to fetch the CountryInstance - :param iso_country: The iso_country - :returns: twilio.rest.pricing.v1.phone_number.country.CountryContext - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryContext + :returns: The fetched CountryInstance """ - return CountryContext(self._version, iso_country=iso_country, ) - def __repr__(self): + 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 - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) class CountryPage(Page): - """ """ - def __init__(self, version, response, solution): + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: """ - Initialize the CountryPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Build an instance of CountryInstance - :returns: twilio.rest.pricing.v1.phone_number.country.CountryPage - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryPage + :param payload: Payload response from the API """ - super(CountryPage, self).__init__(version, response) + return CountryInstance(self._version, payload) - # Path Solution - self._solution = solution + def __repr__(self) -> str: + """ + Provide a friendly representation - def get_instance(self, payload): + :returns: Machine friendly representation """ - Build an instance of CountryInstance + return "" - :param dict payload: Payload response from the API - :returns: twilio.rest.pricing.v1.phone_number.country.CountryInstance - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryInstance - """ - return CountryInstance(self._version, payload, ) +class CountryList(ListResource): - def __repr__(self): + def __init__(self, version: Version): """ - Provide a friendly representation + Initialize the CountryList + + :param version: Version that contains the resource - :returns: Machine friendly representation - :rtype: str """ - return '' + super().__init__(version) + self._uri = "/PhoneNumbers/Countries" -class CountryContext(InstanceContext): - """ """ + 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) - def __init__(self, version, iso_country): + :returns: Generator that will yield up to limit results """ - Initialize the CountryContext + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - :param Version version: Version that contains the resource - :param iso_country: The iso_country + return self._version.stream(page, limits["limit"]) - :returns: twilio.rest.pricing.v1.phone_number.country.CountryContext - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryContext + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CountryInstance]: """ - super(CountryContext, self).__init__(version) + 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. - # Path Solution - self._solution = {'iso_country': iso_country, } - self._uri = '/PhoneNumbers/Countries/{iso_country}'.format(**self._solution) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - def fetch(self): + :returns: Generator that will yield up to limit results """ - Fetch a CountryInstance + 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"]) - :returns: Fetched CountryInstance - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryInstance + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: """ - params = values.of({}) + Lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + 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, + ) ) - return CountryInstance(self._version, payload, iso_country=self._solution['iso_country'], ) + 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. - def __repr__(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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: """ - Provide a friendly representation + Retrieve a single page of CountryInstance records from the API. + Request is executed immediately - :returns: Machine friendly representation - :rtype: str + :param page_token: PageToken provided by the API + :param page_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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) -class CountryInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) - def __init__(self, version, payload, iso_country=None): + 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: """ - Initialize the CountryInstance + Asynchronously retrieve a single page of CountryInstance records from the API. + Request is executed immediately - :returns: twilio.rest.pricing.v1.phone_number.country.CountryInstance - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryInstance + :param page_token: PageToken provided by the API + :param page_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 """ - super(CountryInstance, self).__init__(version) + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - # Marshaled Properties - self._properties = { - 'country': payload['country'], - 'iso_country': payload['iso_country'], - 'url': payload['url'], - 'phone_number_prices': payload.get('phone_number_prices'), - 'price_unit': payload.get('price_unit'), - } + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - # Context - self._context = None - self._solution = {'iso_country': iso_country or self._properties['iso_country'], } + headers["Accept"] = "application/json" - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) - :returns: CountryContext for this CountryInstance - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryContext + def get_page(self, target_url: str) -> CountryPage: """ - if self._context is None: - self._context = CountryContext(self._version, iso_country=self._solution['iso_country'], ) - return self._context + Retrieve a specific page of CountryInstance records from the API. + Request is executed immediately - @property - def country(self): - """ - :returns: The country - :rtype: unicode - """ - return self._properties['country'] + :param target_url: API-generated URL for the requested results page - @property - def iso_country(self): - """ - :returns: The iso_country - :rtype: unicode + :returns: Page of CountryInstance """ - return self._properties['iso_country'] + response = self._version.domain.twilio.request("GET", target_url) + return CountryPage(self._version, response) - @property - def phone_number_prices(self): - """ - :returns: The phone_number_prices - :rtype: unicode + async def get_page_async(self, target_url: str) -> CountryPage: """ - return self._properties['phone_number_prices'] + Asynchronously retrieve a specific page of CountryInstance records from the API. + Request is executed immediately - @property - def price_unit(self): - """ - :returns: The price_unit - :rtype: unicode + :param target_url: API-generated URL for the requested results page + + :returns: Page of CountryInstance """ - return self._properties['price_unit'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return CountryPage(self._version, response) - @property - def url(self): + def get(self, iso_country: str) -> CountryContext: """ - :returns: The url - :rtype: unicode + 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 self._properties['url'] + return CountryContext(self._version, iso_country=iso_country) - def fetch(self): + def __call__(self, iso_country: str) -> CountryContext: """ - Fetch a CountryInstance + Constructs a CountryContext - :returns: Fetched CountryInstance - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryInstance + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. """ - return self._proxy.fetch() + return CountryContext(self._version, iso_country=iso_country) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/pricing/v1/voice/__init__.py b/twilio/rest/pricing/v1/voice/__init__.py index aa5fd3f71a..a801a30089 100644 --- a/twilio/rest/pricing/v1/voice/__init__.py +++ b/twilio/rest/pricing/v1/voice/__init__.py @@ -1,160 +1,65 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base.instance_resource import InstanceResource +from typing import Optional + + from twilio.base.list_resource import ListResource -from twilio.base.page import Page +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): + def __init__(self, version: Version): """ Initialize the VoiceList - :param Version version: Version that contains the resource + :param version: Version that contains the resource - :returns: twilio.rest.pricing.v1.voice.VoiceList - :rtype: twilio.rest.pricing.v1.voice.VoiceList """ - super(VoiceList, self).__init__(version) + super().__init__(version) - # Path Solution - self._solution = {} + self._uri = "/Voice" - # Components - self._numbers = None - self._countries = None + self._countries: Optional[CountryList] = None + self._numbers: Optional[NumberList] = None @property - def numbers(self): - """ - Access the numbers - - :returns: twilio.rest.pricing.v1.voice.number.NumberList - :rtype: twilio.rest.pricing.v1.voice.number.NumberList - """ - if self._numbers is None: - self._numbers = NumberList(self._version, ) - return self._numbers - - @property - def countries(self): + def countries(self) -> CountryList: """ Access the countries - - :returns: twilio.rest.pricing.v1.voice.country.CountryList - :rtype: twilio.rest.pricing.v1.voice.country.CountryList """ if self._countries is None: - self._countries = CountryList(self._version, ) + self._countries = CountryList(self._version) return self._countries - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class VoicePage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the VoicePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.pricing.v1.voice.VoicePage - :rtype: twilio.rest.pricing.v1.voice.VoicePage - """ - super(VoicePage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of VoiceInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.pricing.v1.voice.VoiceInstance - :rtype: twilio.rest.pricing.v1.voice.VoiceInstance - """ - return VoiceInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class VoiceInstance(InstanceResource): - """ """ - - def __init__(self, version, payload): - """ - Initialize the VoiceInstance - - :returns: twilio.rest.pricing.v1.voice.VoiceInstance - :rtype: twilio.rest.pricing.v1.voice.VoiceInstance - """ - super(VoiceInstance, self).__init__(version) - - # Marshaled Properties - self._properties = {'name': payload['name'], 'url': payload['url'], 'links': payload['links'], } - - # Context - self._context = None - self._solution = {} - - @property - def name(self): - """ - :returns: The name - :rtype: unicode - """ - return self._properties['name'] - @property - def url(self): + def numbers(self) -> NumberList: """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def links(self): - """ - :returns: The links - :rtype: unicode + Access the numbers """ - return self._properties['links'] + if self._numbers is None: + self._numbers = NumberList(self._version) + return self._numbers - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/pricing/v1/voice/country.py b/twilio/rest/pricing/v1/voice/country.py index 60a15876c8..7fb0da883a 100644 --- a/twilio/rest/pricing/v1/voice/country.py +++ b/twilio/rest/pricing/v1/voice/country.py @@ -1,337 +1,417 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 CountryList(ListResource): - """ """ - - def __init__(self, version): - """ - Initialize the CountryList +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") - :param Version version: Version that contains the resource + self._solution = { + "iso_country": iso_country or self.iso_country, + } + self._context: Optional[CountryContext] = None - :returns: twilio.rest.pricing.v1.voice.country.CountryList - :rtype: twilio.rest.pricing.v1.voice.country.CountryList + @property + def _proxy(self) -> "CountryContext": """ - super(CountryList, self).__init__(version) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - # Path Solution - self._solution = {} - self._uri = '/Voice/Countries'.format(**self._solution) + :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 stream(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the CountryInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.pricing.v1.voice.country.CountryInstance] + :returns: The fetched CountryInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(page_size=limits['page_size'], ) + async def fetch_async(self) -> "CountryInstance": + """ + Asynchronous coroutine to fetch the CountryInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + return await self._proxy.fetch_async() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.pricing.v1.voice.country.CountryInstance] + def __repr__(self) -> str: """ - return list(self.stream(limit=limit, page_size=page_size, )) + Provide a friendly representation - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + :returns: Machine friendly representation """ - Retrieve a single page of CountryInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of CountryInstance - :rtype: twilio.rest.pricing.v1.voice.country.CountryPage +class CountryContext(InstanceContext): + + def __init__(self, version: Version, iso_country: str): """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the CountryContext - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + :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) - return CountryPage(self._version, response, self._solution) + # Path Solution + self._solution = { + "iso_country": iso_country, + } + self._uri = "/Voice/Countries/{iso_country}".format(**self._solution) - def get_page(self, target_url): + def fetch(self) -> CountryInstance: """ - Retrieve a specific page of CountryInstance records from the API. - Request is executed immediately + Fetch the CountryInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of CountryInstance - :rtype: twilio.rest.pricing.v1.voice.country.CountryPage + :returns: The fetched CountryInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return CountryPage(self._version, response, self._solution) + headers = values.of({}) - def get(self, iso_country): - """ - Constructs a CountryContext + headers["Accept"] = "application/json" - :param iso_country: The iso_country + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.pricing.v1.voice.country.CountryContext - :rtype: twilio.rest.pricing.v1.voice.country.CountryContext - """ - return CountryContext(self._version, iso_country=iso_country, ) + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) - def __call__(self, iso_country): + async def fetch_async(self) -> CountryInstance: """ - Constructs a CountryContext + Asynchronous coroutine to fetch the CountryInstance - :param iso_country: The iso_country - :returns: twilio.rest.pricing.v1.voice.country.CountryContext - :rtype: twilio.rest.pricing.v1.voice.country.CountryContext + :returns: The fetched CountryInstance """ - return CountryContext(self._version, iso_country=iso_country, ) - def __repr__(self): + 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 - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) class CountryPage(Page): - """ """ - def __init__(self, version, response, solution): + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: """ - Initialize the CountryPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Build an instance of CountryInstance - :returns: twilio.rest.pricing.v1.voice.country.CountryPage - :rtype: twilio.rest.pricing.v1.voice.country.CountryPage + :param payload: Payload response from the API """ - super(CountryPage, self).__init__(version, response) + return CountryInstance(self._version, payload) - # Path Solution - self._solution = solution + def __repr__(self) -> str: + """ + Provide a friendly representation - def get_instance(self, payload): + :returns: Machine friendly representation """ - Build an instance of CountryInstance + return "" - :param dict payload: Payload response from the API - :returns: twilio.rest.pricing.v1.voice.country.CountryInstance - :rtype: twilio.rest.pricing.v1.voice.country.CountryInstance - """ - return CountryInstance(self._version, payload, ) +class CountryList(ListResource): - def __repr__(self): + def __init__(self, version: Version): """ - Provide a friendly representation + Initialize the CountryList + + :param version: Version that contains the resource - :returns: Machine friendly representation - :rtype: str """ - return '' + super().__init__(version) + self._uri = "/Voice/Countries" -class CountryContext(InstanceContext): - """ """ + 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) - def __init__(self, version, iso_country): + :returns: Generator that will yield up to limit results """ - Initialize the CountryContext + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - :param Version version: Version that contains the resource - :param iso_country: The iso_country + return self._version.stream(page, limits["limit"]) - :returns: twilio.rest.pricing.v1.voice.country.CountryContext - :rtype: twilio.rest.pricing.v1.voice.country.CountryContext + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CountryInstance]: """ - super(CountryContext, self).__init__(version) + 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. - # Path Solution - self._solution = {'iso_country': iso_country, } - self._uri = '/Voice/Countries/{iso_country}'.format(**self._solution) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - def fetch(self): + :returns: Generator that will yield up to limit results """ - Fetch a CountryInstance + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - :returns: Fetched CountryInstance - :rtype: twilio.rest.pricing.v1.voice.country.CountryInstance + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: """ - params = values.of({}) + 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) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) ) - return CountryInstance(self._version, payload, iso_country=self._solution['iso_country'], ) + 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. - def __repr__(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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: """ - Provide a friendly representation + Retrieve a single page of CountryInstance records from the API. + Request is executed immediately - :returns: Machine friendly representation - :rtype: str + :param page_token: PageToken provided by the API + :param page_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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) -class CountryInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) - def __init__(self, version, payload, iso_country=None): + 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: """ - Initialize the CountryInstance + 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: twilio.rest.pricing.v1.voice.country.CountryInstance - :rtype: twilio.rest.pricing.v1.voice.country.CountryInstance + :returns: Page of CountryInstance """ - super(CountryInstance, self).__init__(version) + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - # Marshaled Properties - self._properties = { - 'country': payload['country'], - 'iso_country': payload['iso_country'], - 'url': payload['url'], - 'outbound_prefix_prices': payload.get('outbound_prefix_prices'), - 'inbound_call_prices': payload.get('inbound_call_prices'), - 'price_unit': payload.get('price_unit'), - } + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - # Context - self._context = None - self._solution = {'iso_country': iso_country or self._properties['iso_country'], } + headers["Accept"] = "application/json" - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) - :returns: CountryContext for this CountryInstance - :rtype: twilio.rest.pricing.v1.voice.country.CountryContext + def get_page(self, target_url: str) -> CountryPage: """ - if self._context is None: - self._context = CountryContext(self._version, iso_country=self._solution['iso_country'], ) - return self._context + Retrieve a specific page of CountryInstance records from the API. + Request is executed immediately - @property - def country(self): - """ - :returns: The country - :rtype: unicode - """ - return self._properties['country'] + :param target_url: API-generated URL for the requested results page - @property - def iso_country(self): - """ - :returns: The iso_country - :rtype: unicode + :returns: Page of CountryInstance """ - return self._properties['iso_country'] + response = self._version.domain.twilio.request("GET", target_url) + return CountryPage(self._version, response) - @property - def outbound_prefix_prices(self): - """ - :returns: The outbound_prefix_prices - :rtype: unicode + async def get_page_async(self, target_url: str) -> CountryPage: """ - return self._properties['outbound_prefix_prices'] + Asynchronously retrieve a specific page of CountryInstance records from the API. + Request is executed immediately - @property - def inbound_call_prices(self): - """ - :returns: The inbound_call_prices - :rtype: unicode - """ - return self._properties['inbound_call_prices'] + :param target_url: API-generated URL for the requested results page - @property - def price_unit(self): - """ - :returns: The price_unit - :rtype: unicode + :returns: Page of CountryInstance """ - return self._properties['price_unit'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return CountryPage(self._version, response) - @property - def url(self): + def get(self, iso_country: str) -> CountryContext: """ - :returns: The url - :rtype: unicode + 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 self._properties['url'] + return CountryContext(self._version, iso_country=iso_country) - def fetch(self): + def __call__(self, iso_country: str) -> CountryContext: """ - Fetch a CountryInstance + Constructs a CountryContext - :returns: Fetched CountryInstance - :rtype: twilio.rest.pricing.v1.voice.country.CountryInstance + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. """ - return self._proxy.fetch() + return CountryContext(self._version, iso_country=iso_country) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/pricing/v1/voice/number.py b/twilio/rest/pricing/v1/voice/number.py index 1c1fff05dd..5bff8cd5d6 100644 --- a/twilio/rest/pricing/v1/voice/number.py +++ b/twilio/rest/pricing/v1/voice/number.py @@ -1,264 +1,197 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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.page import Page +from twilio.base.version import Version -class NumberList(ListResource): - """ """ +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 - def __init__(self, version): + @property + def _proxy(self) -> "NumberContext": """ - Initialize the NumberList - - :param Version version: Version that contains the resource + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: twilio.rest.pricing.v1.voice.number.NumberList - :rtype: twilio.rest.pricing.v1.voice.number.NumberList + :returns: NumberContext for this NumberInstance """ - super(NumberList, self).__init__(version) - - # Path Solution - self._solution = {} + if self._context is None: + self._context = NumberContext( + self._version, + number=self._solution["number"], + ) + return self._context - def get(self, number): + def fetch(self) -> "NumberInstance": """ - Constructs a NumberContext + Fetch the NumberInstance - :param number: The number - :returns: twilio.rest.pricing.v1.voice.number.NumberContext - :rtype: twilio.rest.pricing.v1.voice.number.NumberContext + :returns: The fetched NumberInstance """ - return NumberContext(self._version, number=number, ) + return self._proxy.fetch() - def __call__(self, number): + async def fetch_async(self) -> "NumberInstance": """ - Constructs a NumberContext + Asynchronous coroutine to fetch the NumberInstance - :param number: The number - :returns: twilio.rest.pricing.v1.voice.number.NumberContext - :rtype: twilio.rest.pricing.v1.voice.number.NumberContext + :returns: The fetched NumberInstance """ - return NumberContext(self._version, number=number, ) + return await self._proxy.fetch_async() - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class NumberPage(Page): - """ """ +class NumberContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, number: str): """ - Initialize the NumberPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the NumberContext - :returns: twilio.rest.pricing.v1.voice.number.NumberPage - :rtype: twilio.rest.pricing.v1.voice.number.NumberPage + :param version: Version that contains the resource + :param number: The phone number to fetch. """ - super(NumberPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "number": number, + } + self._uri = "/Voice/Numbers/{number}".format(**self._solution) - def get_instance(self, payload): + def fetch(self) -> NumberInstance: """ - Build an instance of NumberInstance + Fetch the NumberInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.pricing.v1.voice.number.NumberInstance - :rtype: twilio.rest.pricing.v1.voice.number.NumberInstance + :returns: The fetched NumberInstance """ - return NumberInstance(self._version, payload, ) - def __repr__(self): - """ - Provide a friendly representation + headers = values.of({}) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Accept"] = "application/json" + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) -class NumberContext(InstanceContext): - """ """ + return NumberInstance( + self._version, + payload, + number=self._solution["number"], + ) - def __init__(self, version, number): + async def fetch_async(self) -> NumberInstance: """ - Initialize the NumberContext + Asynchronous coroutine to fetch the NumberInstance - :param Version version: Version that contains the resource - :param number: The number - :returns: twilio.rest.pricing.v1.voice.number.NumberContext - :rtype: twilio.rest.pricing.v1.voice.number.NumberContext + :returns: The fetched NumberInstance """ - super(NumberContext, self).__init__(version) - # Path Solution - self._solution = {'number': number, } - self._uri = '/Voice/Numbers/{number}'.format(**self._solution) + headers = values.of({}) - def fetch(self): - """ - Fetch a NumberInstance + headers["Accept"] = "application/json" - :returns: Fetched NumberInstance - :rtype: twilio.rest.pricing.v1.voice.number.NumberInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers ) - return NumberInstance(self._version, payload, number=self._solution['number'], ) + return NumberInstance( + self._version, + payload, + number=self._solution["number"], + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class NumberInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, number=None): - """ - Initialize the NumberInstance - - :returns: twilio.rest.pricing.v1.voice.number.NumberInstance - :rtype: twilio.rest.pricing.v1.voice.number.NumberInstance - """ - super(NumberInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'number': payload['number'], - 'country': payload['country'], - 'iso_country': payload['iso_country'], - 'outbound_call_price': payload['outbound_call_price'], - 'inbound_call_price': payload['inbound_call_price'], - 'price_unit': payload['price_unit'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = {'number': number or self._properties['number'], } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.pricing.v1.voice.number.NumberContext """ - if self._context is None: - self._context = NumberContext(self._version, number=self._solution['number'], ) - return self._context + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def number(self): - """ - :returns: The number - :rtype: unicode - """ - return self._properties['number'] - @property - def country(self): - """ - :returns: The country - :rtype: unicode - """ - return self._properties['country'] +class NumberList(ListResource): - @property - def iso_country(self): - """ - :returns: The iso_country - :rtype: unicode + def __init__(self, version: Version): """ - return self._properties['iso_country'] + Initialize the NumberList - @property - def outbound_call_price(self): - """ - :returns: The outbound_call_price - :rtype: unicode - """ - return self._properties['outbound_call_price'] + :param version: Version that contains the resource - @property - def inbound_call_price(self): - """ - :returns: The inbound_call_price - :rtype: unicode """ - return self._properties['inbound_call_price'] + super().__init__(version) - @property - def price_unit(self): + def get(self, number: str) -> NumberContext: """ - :returns: The price_unit - :rtype: unicode - """ - return self._properties['price_unit'] + Constructs a NumberContext - @property - def url(self): - """ - :returns: The url - :rtype: unicode + :param number: The phone number to fetch. """ - return self._properties['url'] + return NumberContext(self._version, number=number) - def fetch(self): + def __call__(self, number: str) -> NumberContext: """ - Fetch a NumberInstance + Constructs a NumberContext - :returns: Fetched NumberInstance - :rtype: twilio.rest.pricing.v1.voice.number.NumberInstance + :param number: The phone number to fetch. """ - return self._proxy.fetch() + return NumberContext(self._version, number=number) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" 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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" 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 "" diff --git a/twilio/rest/proxy/__init__.py b/twilio/rest/proxy/__init__.py index 71283f0271..aec2a3d1af 100644 --- a/twilio/rest/proxy/__init__.py +++ b/twilio/rest/proxy/__init__.py @@ -1,53 +1,15 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" +from warnings import warn -from twilio.base.domain import Domain -from twilio.rest.proxy.v1 import V1 +from twilio.rest.proxy.ProxyBase import ProxyBase +from twilio.rest.proxy.v1.service import ServiceList -class Proxy(Domain): - - def __init__(self, twilio): - """ - Initialize the Proxy Domain - - :returns: Domain for Proxy - :rtype: twilio.rest.proxy.Proxy - """ - super(Proxy, self).__init__(twilio) - - self.base_url = 'https://proxy.twilio.com' - - # Versions - self._v1 = None - +class Proxy(ProxyBase): @property - def v1(self): - """ - :returns: Version v1 of proxy - :rtype: twilio.rest.proxy.v1.V1 - """ - if self._v1 is None: - self._v1 = V1(self) - return self._v1 - - @property - def services(self): - """ - :rtype: twilio.rest.proxy.v1.service.ServiceList - """ + def services(self) -> ServiceList: + warn( + "services is deprecated. Use v1.services instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v1.services - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/proxy/v1/__init__.py b/twilio/rest/proxy/v1/__init__.py index 73053a8071..83737dc0fb 100644 --- a/twilio/rest/proxy/v1/__init__.py +++ b/twilio/rest/proxy/v1/__init__.py @@ -1,42 +1,43 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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): + def __init__(self, domain: Domain): """ Initialize the V1 version of Proxy - :returns: V1 version of Proxy - :rtype: twilio.rest.proxy.v1.V1.V1 + :param domain: The Twilio.proxy domain """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._services = None + super().__init__(domain, "v1") + self._services: Optional[ServiceList] = None @property - def services(self): - """ - :rtype: twilio.rest.proxy.v1.service.ServiceList - """ + def services(self) -> ServiceList: if self._services is None: self._services = ServiceList(self) return self._services - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/proxy/v1/service/__init__.py b/twilio/rest/proxy/v1/service/__init__.py index dbb3299495..ff1e7ed7d7 100644 --- a/twilio/rest/proxy/v1/service/__init__.py +++ b/twilio/rest/proxy/v1/service/__init__.py @@ -1,610 +1,844 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 ServiceList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class ServiceInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the ServiceList + class GeoMatchLevel(object): + AREA_CODE = "area-code" + OVERLAY = "overlay" + RADIUS = "radius" + COUNTRY = "country" - :param Version version: Version that contains the resource + class NumberSelectionBehavior(object): + AVOID_STICKY = "avoid-sticky" + PREFER_STICKY = "prefer-sticky" - :returns: twilio.rest.proxy.v1.service.ServiceList - :rtype: twilio.rest.proxy.v1.service.ServiceList - """ - super(ServiceList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {} - self._uri = '/Services'.format(**self._solution) + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None - def stream(self, limit=None, page_size=None): + @property + def _proxy(self) -> "ServiceContext": """ - 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. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.proxy.v1.service.ServiceInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the ServiceInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists ServiceInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the ServiceInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.proxy.v1.service.ServiceInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "ServiceInstance": """ - Retrieve a single page of ServiceInstance records from the API. - Request is executed immediately + Fetch the ServiceInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of ServiceInstance - :rtype: twilio.rest.proxy.v1.service.ServicePage + :returns: The fetched ServiceInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance - return ServicePage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched ServiceInstance """ - Retrieve a specific page of ServiceInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page + return await self._proxy.fetch_async() - :returns: Page of ServiceInstance - :rtype: twilio.rest.proxy.v1.service.ServicePage + 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": """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Update the ServiceInstance - return ServicePage(self._version, response, self._solution) - - def create(self, unique_name, default_ttl=values.unset, - callback_url=values.unset, geo_match_level=values.unset, - number_selection_behavior=values.unset, - intercept_callback_url=values.unset, - out_of_session_callback_url=values.unset): - """ - Create a new ServiceInstance - - :param unicode unique_name: The human-readable string that uniquely identifies this Service. - :param unicode default_ttl: Default TTL for a Session, in seconds. - :param unicode callback_url: URL Twilio will send callbacks to - :param ServiceInstance.GeoMatchLevel geo_match_level: Whether to find proxy numbers in the same areacode. - :param ServiceInstance.NumberSelectionBehavior number_selection_behavior: What behavior to use when choosing a proxy number. - :param unicode intercept_callback_url: A URL for Twilio call before each Interaction. - :param unicode out_of_session_callback_url: A URL for Twilio call when a new Interaction has no Session. - - :returns: Newly created ServiceInstance - :rtype: twilio.rest.proxy.v1.service.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, - }) + :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. - payload = self._version.create( - 'POST', - self._uri, - data=data, + :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, ) - return ServiceInstance(self._version, payload, ) + 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, + ) - def get(self, sid): + @property + def phone_numbers(self) -> PhoneNumberList: """ - Constructs a ServiceContext - - :param sid: A string that uniquely identifies this Service. - - :returns: twilio.rest.proxy.v1.service.ServiceContext - :rtype: twilio.rest.proxy.v1.service.ServiceContext + Access the phone_numbers """ - return ServiceContext(self._version, sid=sid, ) + return self._proxy.phone_numbers - def __call__(self, sid): + @property + def sessions(self) -> SessionList: """ - Constructs a ServiceContext - - :param sid: A string that uniquely identifies this Service. + Access the sessions + """ + return self._proxy.sessions - :returns: twilio.rest.proxy.v1.service.ServiceContext - :rtype: twilio.rest.proxy.v1.service.ServiceContext + @property + def short_codes(self) -> ShortCodeList: """ - return ServiceContext(self._version, sid=sid, ) + Access the short_codes + """ + return self._proxy.short_codes - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ServicePage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class ServiceContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the ServicePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the ServiceContext - :returns: twilio.rest.proxy.v1.service.ServicePage - :rtype: twilio.rest.proxy.v1.service.ServicePage + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. """ - super(ServicePage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) - def get_instance(self, payload): + self._phone_numbers: Optional[PhoneNumberList] = None + self._sessions: Optional[SessionList] = None + self._short_codes: Optional[ShortCodeList] = None + + def delete(self) -> bool: """ - Build an instance of ServiceInstance + Deletes the ServiceInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.proxy.v1.service.ServiceInstance - :rtype: twilio.rest.proxy.v1.service.ServiceInstance + :returns: True if delete succeeds, False otherwise """ - return ServiceInstance(self._version, payload, ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the ServiceInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class ServiceContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, sid): + def fetch(self) -> ServiceInstance: """ - Initialize the ServiceContext + Fetch the ServiceInstance - :param Version version: Version that contains the resource - :param sid: A string that uniquely identifies this Service. - :returns: twilio.rest.proxy.v1.service.ServiceContext - :rtype: twilio.rest.proxy.v1.service.ServiceContext + :returns: The fetched ServiceInstance """ - super(ServiceContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Services/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - # Dependents - self._sessions = None - self._phone_numbers = None - self._short_codes = None + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: """ - Fetch a ServiceInstance + Asynchronous coroutine to fetch the ServiceInstance - :returns: Fetched ServiceInstance - :rtype: twilio.rest.proxy.v1.service.ServiceInstance + + :returns: The fetched ServiceInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) + headers = values.of({}) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" - def delete(self): - """ - Deletes the ServiceInstance + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def update(self, unique_name=values.unset, default_ttl=values.unset, - callback_url=values.unset, geo_match_level=values.unset, - number_selection_behavior=values.unset, - intercept_callback_url=values.unset, - out_of_session_callback_url=values.unset): + 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 unicode unique_name: A human readable description of this resource. - :param unicode default_ttl: Default TTL for a Session, in seconds. - :param unicode callback_url: URL Twilio will send callbacks to - :param ServiceInstance.GeoMatchLevel geo_match_level: Whether to find proxy numbers in the same areacode. - :param ServiceInstance.NumberSelectionBehavior number_selection_behavior: What behavior to use when choosing a proxy number. - :param unicode intercept_callback_url: A URL for Twilio call before each Interaction. - :param unicode out_of_session_callback_url: A URL for Twilio call when a new Interaction has no Session. - - :returns: Updated ServiceInstance - :rtype: twilio.rest.proxy.v1.service.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, - }) + :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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + 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({}) - @property - def sessions(self): - """ - Access the sessions + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: twilio.rest.proxy.v1.service.session.SessionList - :rtype: twilio.rest.proxy.v1.service.session.SessionList - """ - if self._sessions is None: - self._sessions = SessionList(self._version, service_sid=self._solution['sid'], ) - return self._sessions + 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): + def phone_numbers(self) -> PhoneNumberList: """ Access the phone_numbers - - :returns: twilio.rest.proxy.v1.service.phone_number.PhoneNumberList - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberList """ if self._phone_numbers is None: - self._phone_numbers = PhoneNumberList(self._version, service_sid=self._solution['sid'], ) + self._phone_numbers = PhoneNumberList( + self._version, + self._solution["sid"], + ) return self._phone_numbers @property - def short_codes(self): + def sessions(self) -> SessionList: """ - Access the short_codes + Access the sessions + """ + if self._sessions is None: + self._sessions = SessionList( + self._version, + self._solution["sid"], + ) + return self._sessions - :returns: twilio.rest.proxy.v1.service.short_code.ShortCodeList - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeList + @property + def short_codes(self) -> ShortCodeList: + """ + Access the short_codes """ if self._short_codes is None: - self._short_codes = ShortCodeList(self._version, service_sid=self._solution['sid'], ) + self._short_codes = ShortCodeList( + self._version, + self._solution["sid"], + ) return self._short_codes - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class ServiceInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - class GeoMatchLevel(object): - AREA_CODE = "area-code" - OVERLAY = "overlay" - RADIUS = "radius" - COUNTRY = "country" + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - class NumberSelectionBehavior(object): - AVOID_STICKY = "avoid-sticky" - PREFER_STICKY = "prefer-sticky" - def __init__(self, version, payload, sid=None): - """ - Initialize the ServiceInstance - - :returns: twilio.rest.proxy.v1.service.ServiceInstance - :rtype: twilio.rest.proxy.v1.service.ServiceInstance - """ - super(ServiceInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'unique_name': payload['unique_name'], - 'account_sid': payload['account_sid'], - 'callback_url': payload['callback_url'], - 'default_ttl': deserialize.integer(payload['default_ttl']), - 'number_selection_behavior': payload['number_selection_behavior'], - 'geo_match_level': payload['geo_match_level'], - 'intercept_callback_url': payload['intercept_callback_url'], - 'out_of_session_callback_url': payload['out_of_session_callback_url'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - 'links': payload['links'], - } - - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } +class ServicePage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of ServiceInstance - :returns: ServiceContext for this ServiceInstance - :rtype: twilio.rest.proxy.v1.service.ServiceContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = ServiceContext(self._version, sid=self._solution['sid'], ) - return self._context + return ServiceInstance(self._version, payload) - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Service. - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['sid'] + Provide a friendly representation - @property - def unique_name(self): - """ - :returns: A human readable description of this resource. - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['unique_name'] + return "" - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def callback_url(self): - """ - :returns: URL Twilio will send callbacks to - :rtype: unicode - """ - return self._properties['callback_url'] +class ServiceList(ListResource): - @property - def default_ttl(self): - """ - :returns: Default TTL for a Session, in seconds. - :rtype: unicode + def __init__(self, version: Version): """ - return self._properties['default_ttl'] + Initialize the ServiceList - @property - def number_selection_behavior(self): - """ - :returns: What behavior to use when choosing a proxy number. - :rtype: ServiceInstance.NumberSelectionBehavior - """ - return self._properties['number_selection_behavior'] + :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"}) - @property - def geo_match_level(self): - """ - :returns: Whether to find proxy numbers in the same areacode. - :rtype: ServiceInstance.GeoMatchLevel - """ - return self._properties['geo_match_level'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def intercept_callback_url(self): - """ - :returns: A URL for Twilio call before each Interaction. - :rtype: unicode - """ - return self._properties['intercept_callback_url'] + headers["Accept"] = "application/json" - @property - def out_of_session_callback_url(self): - """ - :returns: A URL for Twilio call when a new Interaction has no Session. - :rtype: unicode - """ - return self._properties['out_of_session_callback_url'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def date_created(self): - """ - :returns: The date this Service was created - :rtype: datetime + 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]: """ - return self._properties['date_created'] + 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. - @property - def date_updated(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The date this Service was updated - :rtype: datetime + 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]: """ - return self._properties['date_updated'] + 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. - @property - def url(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The URL of this resource. - :rtype: unicode + 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]: """ - return self._properties['url'] + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def links(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: Nested resource URLs. - :rtype: unicode + 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]: """ - return self._properties['links'] + 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. - def fetch(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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: """ - Fetch a ServiceInstance + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - :returns: Fetched ServiceInstance - :rtype: twilio.rest.proxy.v1.service.ServiceInstance + :param page_token: PageToken provided by the API + :param page_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 """ - return self._proxy.fetch() + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - def delete(self): + headers = values.of({"Content-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: """ - Deletes the ServiceInstance + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param page_token: PageToken provided by the API + :param page_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 """ - return self._proxy.delete() + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def update(self, unique_name=values.unset, default_ttl=values.unset, - callback_url=values.unset, geo_match_level=values.unset, - number_selection_behavior=values.unset, - intercept_callback_url=values.unset, - out_of_session_callback_url=values.unset): + 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: """ - Update the ServiceInstance + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately - :param unicode unique_name: A human readable description of this resource. - :param unicode default_ttl: Default TTL for a Session, in seconds. - :param unicode callback_url: URL Twilio will send callbacks to - :param ServiceInstance.GeoMatchLevel geo_match_level: Whether to find proxy numbers in the same areacode. - :param ServiceInstance.NumberSelectionBehavior number_selection_behavior: What behavior to use when choosing a proxy number. - :param unicode intercept_callback_url: A URL for Twilio call before each Interaction. - :param unicode out_of_session_callback_url: A URL for Twilio call when a new Interaction has no Session. + :param target_url: API-generated URL for the requested results page - :returns: Updated ServiceInstance - :rtype: twilio.rest.proxy.v1.service.ServiceInstance + :returns: Page of 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, - ) + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) - @property - def sessions(self): + async def get_page_async(self, target_url: str) -> ServicePage: """ - Access the sessions + 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: twilio.rest.proxy.v1.service.session.SessionList - :rtype: twilio.rest.proxy.v1.service.session.SessionList + :returns: Page of ServiceInstance """ - return self._proxy.sessions + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) - @property - def phone_numbers(self): + def get(self, sid: str) -> ServiceContext: """ - Access the phone_numbers + Constructs a ServiceContext - :returns: twilio.rest.proxy.v1.service.phone_number.PhoneNumberList - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberList + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. """ - return self._proxy.phone_numbers + return ServiceContext(self._version, sid=sid) - @property - def short_codes(self): + def __call__(self, sid: str) -> ServiceContext: """ - Access the short_codes + Constructs a ServiceContext - :returns: twilio.rest.proxy.v1.service.short_code.ShortCodeList - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeList + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. """ - return self._proxy.short_codes + return ServiceContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/proxy/v1/service/phone_number.py b/twilio/rest/proxy/v1/service/phone_number.py index ac50864048..3c8517cedd 100644 --- a/twilio/rest/proxy/v1/service/phone_number.py +++ b/twilio/rest/proxy/v1/service/phone_number.py @@ -1,428 +1,662 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 PhoneNumberList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +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 - def __init__(self, version, service_sid): + @property + def _proxy(self) -> "PhoneNumberContext": """ - Initialize the PhoneNumberList - - :param Version version: Version that contains the resource - :param service_sid: Service Sid. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: twilio.rest.proxy.v1.service.phone_number.PhoneNumberList - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberList + :returns: PhoneNumberContext for this PhoneNumberInstance """ - super(PhoneNumberList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/PhoneNumbers'.format(**self._solution) + if self._context is None: + self._context = PhoneNumberContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - def create(self, sid=values.unset, phone_number=values.unset): + def delete(self) -> bool: """ - Create a new PhoneNumberInstance + Deletes the PhoneNumberInstance - :param unicode sid: A string that uniquely identifies this Phone Number. - :param unicode phone_number: The phone_number - :returns: Newly created PhoneNumberInstance - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({'Sid': sid, 'PhoneNumber': phone_number, }) + return self._proxy.delete() - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance - return PhoneNumberInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return await self._proxy.delete_async() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.proxy.v1.service.phone_number.PhoneNumberInstance] + def fetch(self) -> "PhoneNumberInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the PhoneNumberInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched PhoneNumberInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the PhoneNumberInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.proxy.v1.service.phone_number.PhoneNumberInstance] + :returns: The fetched PhoneNumberInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def update( + self, is_reserved: Union[bool, object] = values.unset + ) -> "PhoneNumberInstance": """ - Retrieve a single page of PhoneNumberInstance records from the API. - Request is executed immediately + Update the PhoneNumberInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :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: Page of PhoneNumberInstance - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberPage + :returns: The updated PhoneNumberInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + return self._proxy.update( + is_reserved=is_reserved, ) - return PhoneNumberPage(self._version, response, self._solution) - - def get_page(self, target_url): + async def update_async( + self, is_reserved: Union[bool, object] = values.unset + ) -> "PhoneNumberInstance": """ - Retrieve a specific page of PhoneNumberInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the PhoneNumberInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of PhoneNumberInstance - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberPage + :returns: The updated PhoneNumberInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + is_reserved=is_reserved, ) - return PhoneNumberPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a PhoneNumberContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param sid: A string that uniquely identifies this Phone Number. - :returns: twilio.rest.proxy.v1.service.phone_number.PhoneNumberContext - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberContext +class PhoneNumberContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): """ - return PhoneNumberContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Initialize the PhoneNumberContext - def __call__(self, sid): + :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. """ - Constructs a PhoneNumberContext + super().__init__(version) - :param sid: A string that uniquely identifies this Phone Number. + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/PhoneNumbers/{sid}".format( + **self._solution + ) - :returns: twilio.rest.proxy.v1.service.phone_number.PhoneNumberContext - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberContext + def delete(self) -> bool: """ - return PhoneNumberContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Deletes the PhoneNumberInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class PhoneNumberPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, response, solution): + async def delete_async(self) -> bool: """ - Initialize the PhoneNumberPage + Asynchronous coroutine that deletes the PhoneNumberInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Service Sid. - :returns: twilio.rest.proxy.v1.service.phone_number.PhoneNumberPage - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberPage + :returns: True if delete succeeds, False otherwise """ - super(PhoneNumberPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def get_instance(self, payload): + def fetch(self) -> PhoneNumberInstance: """ - Build an instance of PhoneNumberInstance + Fetch the PhoneNumberInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.proxy.v1.service.phone_number.PhoneNumberInstance - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberInstance + :returns: The fetched PhoneNumberInstance """ - return PhoneNumberInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def __repr__(self): - """ - Provide a friendly representation + headers = values.of({}) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Accept"] = "application/json" + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) -class PhoneNumberContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - def __init__(self, version, service_sid, sid): + async def fetch_async(self) -> PhoneNumberInstance: """ - Initialize the PhoneNumberContext + Asynchronous coroutine to fetch the PhoneNumberInstance - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param sid: A string that uniquely identifies this Phone Number. - :returns: twilio.rest.proxy.v1.service.phone_number.PhoneNumberContext - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberContext + :returns: The fetched PhoneNumberInstance """ - super(PhoneNumberContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/PhoneNumbers/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - def delete(self): + 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: """ - Deletes the PhoneNumberInstance + Update the PhoneNumberInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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._version.delete('delete', self._uri) - def fetch(self): + 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: """ - Fetch a PhoneNumberInstance + Asynchronous coroutine to update the PhoneNumberInstance - :returns: Fetched PhoneNumberInstance - :rtype: twilio.rest.proxy.v1.service.phone_number.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 """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class PhoneNumberInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the PhoneNumberInstance - - :returns: twilio.rest.proxy.v1.service.phone_number.PhoneNumberInstance - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberInstance - """ - super(PhoneNumberInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'phone_number': payload['phone_number'], - 'friendly_name': payload['friendly_name'], - 'iso_country': payload['iso_country'], - 'capabilities': payload['capabilities'], - 'url': payload['url'], - } +class PhoneNumberPage(Page): - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + def get_instance(self, payload: Dict[str, Any]) -> PhoneNumberInstance: + """ + Build an instance of PhoneNumberInstance - @property - def _proxy(self): + :param payload: Payload response from the API """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + return PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - :returns: PhoneNumberContext for this PhoneNumberInstance - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberContext + def __repr__(self) -> str: """ - if self._context is None: - self._context = PhoneNumberContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + Provide a friendly representation - @property - def sid(self): + :returns: Machine friendly representation """ - :returns: A string that uniquely identifies this Phone Number. - :rtype: unicode + return "" + + +class PhoneNumberList(ListResource): + + def __init__(self, version: Version, service_sid: str): """ - return self._properties['sid'] + 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. - @property - def account_sid(self): """ - :returns: Account Sid. - :rtype: unicode + 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: """ - return self._properties['account_sid'] + Create the PhoneNumberInstance - @property - def service_sid(self): + :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 """ - :returns: Service Sid. - :rtype: unicode + + 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: """ - return self._properties['service_sid'] + Asynchronously create the PhoneNumberInstance - @property - def date_created(self): + :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 """ - :returns: The date this Phone Number was created - :rtype: datetime + + 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]: """ - return self._properties['date_created'] + 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. - @property - def date_updated(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The date this Phone Number was updated - :rtype: datetime + 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]: """ - return self._properties['date_updated'] + 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. - @property - def phone_number(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The phone number. - :rtype: unicode + 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]: """ - return self._properties['phone_number'] + Lists PhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def friendly_name(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: A human readable description of this resource. - :rtype: unicode + 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]: """ - return self._properties['friendly_name'] + 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. - @property - def iso_country(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: ISO Country Code, - :rtype: unicode + 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: """ - return self._properties['iso_country'] + Retrieve a single page of PhoneNumberInstance records from the API. + Request is executed immediately - @property - def capabilities(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: A list of capabilities. - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['capabilities'] + Asynchronously retrieve a single page of PhoneNumberInstance records from the API. + Request is executed immediately - @property - def url(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The URL of this resource. - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['url'] + 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 - def delete(self): + :returns: Page of PhoneNumberInstance """ - Deletes the PhoneNumberInstance + response = self._version.domain.twilio.request("GET", target_url) + return PhoneNumberPage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def get_page_async(self, target_url: str) -> PhoneNumberPage: """ - return self._proxy.delete() + 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 fetch(self): + def get(self, sid: str) -> PhoneNumberContext: """ - Fetch a PhoneNumberInstance + Constructs a PhoneNumberContext - :returns: Fetched PhoneNumberInstance - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberInstance + :param sid: The Twilio-provided string that uniquely identifies the PhoneNumber resource to update. """ - return self._proxy.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 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/proxy/v1/service/session/__init__.py b/twilio/rest/proxy/v1/service/session/__init__.py index 0b42cc3291..839db075c3 100644 --- a/twilio/rest/proxy/v1/service/session/__init__.py +++ b/twilio/rest/proxy/v1/service/session/__init__.py @@ -1,644 +1,784 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 SessionList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class SessionInstance(InstanceResource): - def __init__(self, version, service_sid): - """ - Initialize the SessionList + class Mode(object): + MESSAGE_ONLY = "message-only" + VOICE_ONLY = "voice-only" + VOICE_AND_MESSAGE = "voice-and-message" - :param Version version: Version that contains the resource - :param service_sid: Service Sid. + class Status(object): + OPEN = "open" + IN_PROGRESS = "in-progress" + CLOSED = "closed" + FAILED = "failed" + UNKNOWN = "unknown" - :returns: twilio.rest.proxy.v1.service.session.SessionList - :rtype: twilio.rest.proxy.v1.service.session.SessionList - """ - super(SessionList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Sessions'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[SessionContext] = None - def stream(self, unique_name=values.unset, status=values.unset, limit=None, - page_size=None): + @property + def _proxy(self) -> "SessionContext": """ - 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. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param unicode unique_name: A unique, developer assigned name of this Session. - :param SessionInstance.Status status: The Status of this Session - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.proxy.v1.service.session.SessionInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the SessionInstance - page = self.page(unique_name=unique_name, status=status, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, unique_name=values.unset, status=values.unset, limit=None, - page_size=None): + async def delete_async(self) -> bool: """ - Lists SessionInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the SessionInstance - :param unicode unique_name: A unique, developer assigned name of this Session. - :param SessionInstance.Status status: The Status of this Session - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.proxy.v1.service.session.SessionInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(unique_name=unique_name, status=status, limit=limit, page_size=page_size, )) + return await self._proxy.delete_async() - def page(self, unique_name=values.unset, status=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "SessionInstance": """ - Retrieve a single page of SessionInstance records from the API. - Request is executed immediately + Fetch the SessionInstance - :param unicode unique_name: A unique, developer assigned name of this Session. - :param SessionInstance.Status status: The Status of this Session - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of SessionInstance - :rtype: twilio.rest.proxy.v1.service.session.SessionPage + :returns: The fetched SessionInstance """ - params = values.of({ - 'UniqueName': unique_name, - 'Status': status, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return SessionPage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "SessionInstance": """ - Retrieve a specific page of SessionInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the SessionInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of SessionInstance - :rtype: twilio.rest.proxy.v1.service.session.SessionPage + :returns: The fetched SessionInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return SessionPage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def create(self, unique_name=values.unset, date_expiry=values.unset, - ttl=values.unset, mode=values.unset, status=values.unset, - participants=values.unset): + def update( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> "SessionInstance": """ - Create a new SessionInstance + Update the SessionInstance - :param unicode unique_name: A unique, developer assigned name of this Session. - :param datetime date_expiry: The date this Session was expiry - :param unicode ttl: TTL for a Session, in seconds. - :param SessionInstance.Mode mode: The Mode of this Session - :param SessionInstance.Status status: The Status of this Session - :param dict participants: A list of phone numbers to add to this Session. + :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: Newly created SessionInstance - :rtype: twilio.rest.proxy.v1.service.session.SessionInstance + :returns: The updated 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)), - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, + return self._proxy.update( + date_expiry=date_expiry, + ttl=ttl, + status=status, ) - return SessionInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def get(self, 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": """ - Constructs a SessionContext + Asynchronous coroutine to update the SessionInstance - :param sid: A string that uniquely identifies this Session. + :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: twilio.rest.proxy.v1.service.session.SessionContext - :rtype: twilio.rest.proxy.v1.service.session.SessionContext + :returns: The updated SessionInstance """ - return SessionContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_async( + date_expiry=date_expiry, + ttl=ttl, + status=status, + ) - def __call__(self, sid): + @property + def interactions(self) -> InteractionList: """ - Constructs a SessionContext - - :param sid: A string that uniquely identifies this Session. + Access the interactions + """ + return self._proxy.interactions - :returns: twilio.rest.proxy.v1.service.session.SessionContext - :rtype: twilio.rest.proxy.v1.service.session.SessionContext + @property + def participants(self) -> ParticipantList: """ - return SessionContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Access the participants + """ + return self._proxy.participants - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class SessionPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class SessionContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the SessionPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Service Sid. + Initialize the SessionContext - :returns: twilio.rest.proxy.v1.service.session.SessionPage - :rtype: twilio.rest.proxy.v1.service.session.SessionPage + :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(SessionPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Sessions/{sid}".format(**self._solution) - def get_instance(self, payload): + self._interactions: Optional[InteractionList] = None + self._participants: Optional[ParticipantList] = None + + def delete(self) -> bool: """ - Build an instance of SessionInstance + Deletes the SessionInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.proxy.v1.service.session.SessionInstance - :rtype: twilio.rest.proxy.v1.service.session.SessionInstance + :returns: True if delete succeeds, False otherwise """ - return SessionInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the SessionInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class SessionContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, service_sid, sid): + def fetch(self) -> SessionInstance: """ - Initialize the SessionContext + Fetch the SessionInstance - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param sid: A string that uniquely identifies this Session. - :returns: twilio.rest.proxy.v1.service.session.SessionContext - :rtype: twilio.rest.proxy.v1.service.session.SessionContext + :returns: The fetched SessionInstance """ - super(SessionContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Sessions/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._interactions = None - self._participants = None + headers["Accept"] = "application/json" - def fetch(self): + 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: """ - Fetch a SessionInstance + Asynchronous coroutine to fetch the SessionInstance + - :returns: Fetched SessionInstance - :rtype: twilio.rest.proxy.v1.service.session.SessionInstance + :returns: The fetched SessionInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + def update( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> SessionInstance: """ - Deletes the SessionInstance + Update the SessionInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :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: - def update(self, unique_name=values.unset, date_expiry=values.unset, - ttl=values.unset, mode=values.unset, status=values.unset, - participants=values.unset): + :returns: The updated SessionInstance """ - Update the SessionInstance - :param unicode unique_name: A unique, developer assigned name of this Session. - :param datetime date_expiry: The date this Session was expiry - :param unicode ttl: TTL for a Session, in seconds. - :param SessionInstance.Mode mode: The Mode of this Session - :param SessionInstance.Status status: The Status of this Session - :param dict participants: A list of phone numbers to add to this Session. - - :returns: Updated SessionInstance - :rtype: twilio.rest.proxy.v1.service.session.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)), - }) + 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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) return SessionInstance( self._version, payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + 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): + def interactions(self) -> InteractionList: """ Access the interactions - - :returns: twilio.rest.proxy.v1.service.session.interaction.InteractionList - :rtype: twilio.rest.proxy.v1.service.session.interaction.InteractionList """ if self._interactions is None: self._interactions = InteractionList( self._version, - service_sid=self._solution['service_sid'], - session_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) return self._interactions @property - def participants(self): + def participants(self) -> ParticipantList: """ Access the participants - - :returns: twilio.rest.proxy.v1.service.session.participant.ParticipantList - :rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantList """ if self._participants is None: self._participants = ParticipantList( self._version, - service_sid=self._solution['service_sid'], - session_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) return self._participants - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class SessionInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - class Status(object): - IN_PROGRESS = "in-progress" - CLOSED = "closed" - FAILED = "failed" - UNKNOWN = "unknown" - COMPLETED = "completed" - class Mode(object): - MESSAGE_ONLY = "message-only" - VOICE_ONLY = "voice-only" - VOICE_AND_MESSAGE = "voice-and-message" - - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the SessionInstance - - :returns: twilio.rest.proxy.v1.service.session.SessionInstance - :rtype: twilio.rest.proxy.v1.service.session.SessionInstance - """ - super(SessionInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'service_sid': payload['service_sid'], - 'account_sid': payload['account_sid'], - 'date_started': deserialize.iso8601_datetime(payload['date_started']), - 'date_ended': deserialize.iso8601_datetime(payload['date_ended']), - 'date_last_interaction': deserialize.iso8601_datetime(payload['date_last_interaction']), - 'date_expiry': deserialize.iso8601_datetime(payload['date_expiry']), - 'unique_name': payload['unique_name'], - 'status': payload['status'], - 'closed_reason': payload['closed_reason'], - 'ttl': deserialize.integer(payload['ttl']), - 'mode': payload['mode'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - 'links': payload['links'], - } - - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } +class SessionPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> SessionInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of SessionInstance - :returns: SessionContext for this SessionInstance - :rtype: twilio.rest.proxy.v1.service.session.SessionContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = SessionContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + return SessionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def sid(self): + def __repr__(self) -> str: """ - :returns: A string that uniquely identifies this Session. - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def service_sid(self): - """ - :returns: Service Sid. - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['service_sid'] + return "" - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def date_started(self): - """ - :returns: The date this Session was started - :rtype: datetime - """ - return self._properties['date_started'] +class SessionList(ListResource): - @property - def date_ended(self): - """ - :returns: The date this Session was ended - :rtype: datetime + def __init__(self, version: Version, service_sid: str): """ - return self._properties['date_ended'] + Initialize the SessionList - @property - def date_last_interaction(self): - """ - :returns: The date this Session was interaction - :rtype: datetime - """ - return self._properties['date_last_interaction'] + :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. - @property - def date_expiry(self): """ - :returns: The date this Session was expiry - :rtype: datetime - """ - return self._properties['date_expiry'] + super().__init__(version) - @property - def unique_name(self): - """ - :returns: A unique, developer assigned name of this Session. - :rtype: unicode - """ - return self._properties['unique_name'] + # 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"}) - @property - def status(self): - """ - :returns: The Status of this Session - :rtype: SessionInstance.Status - """ - return self._properties['status'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def closed_reason(self): - """ - :returns: Reason Session ended. - :rtype: unicode - """ - return self._properties['closed_reason'] + headers["Accept"] = "application/json" - @property - def ttl(self): - """ - :returns: TTL for a Session, in seconds. - :rtype: unicode - """ - return self._properties['ttl'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def mode(self): + 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]: """ - :returns: The Mode of this Session - :rtype: SessionInstance.Mode + 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 """ - return self._properties['mode'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def date_created(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SessionInstance]: """ - :returns: The date this Session was created - :rtype: datetime + 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 """ - return self._properties['date_created'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def date_updated(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SessionInstance]: """ - :returns: The date this Session was updated - :rtype: datetime + 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 self._properties['date_updated'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def url(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SessionInstance]: """ - :returns: The URL of this resource. - :rtype: unicode + 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 self._properties['url'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def links(self): + 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: """ - :returns: Nested resource URLs. - :rtype: unicode + 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 """ - return self._properties['links'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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) - def fetch(self): + 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: """ - Fetch a SessionInstance + 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: Fetched SessionInstance - :rtype: twilio.rest.proxy.v1.service.session.SessionInstance + :returns: Page of SessionInstance """ - return self._proxy.fetch() + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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 delete(self): + def get_page(self, target_url: str) -> SessionPage: """ - Deletes the SessionInstance + Retrieve a specific page of SessionInstance records from the API. + Request is executed immediately - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param target_url: API-generated URL for the requested results page + + :returns: Page of SessionInstance """ - return self._proxy.delete() + response = self._version.domain.twilio.request("GET", target_url) + return SessionPage(self._version, response, self._solution) - def update(self, unique_name=values.unset, date_expiry=values.unset, - ttl=values.unset, mode=values.unset, status=values.unset, - participants=values.unset): + async def get_page_async(self, target_url: str) -> SessionPage: """ - Update the SessionInstance + Asynchronously retrieve a specific page of SessionInstance records from the API. + Request is executed immediately - :param unicode unique_name: A unique, developer assigned name of this Session. - :param datetime date_expiry: The date this Session was expiry - :param unicode ttl: TTL for a Session, in seconds. - :param SessionInstance.Mode mode: The Mode of this Session - :param SessionInstance.Status status: The Status of this Session - :param dict participants: A list of phone numbers to add to this Session. + :param target_url: API-generated URL for the requested results page - :returns: Updated SessionInstance - :rtype: twilio.rest.proxy.v1.service.session.SessionInstance + :returns: Page of SessionInstance """ - return self._proxy.update( - unique_name=unique_name, - date_expiry=date_expiry, - ttl=ttl, - mode=mode, - status=status, - participants=participants, - ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return SessionPage(self._version, response, self._solution) - @property - def interactions(self): + def get(self, sid: str) -> SessionContext: """ - Access the interactions + Constructs a SessionContext - :returns: twilio.rest.proxy.v1.service.session.interaction.InteractionList - :rtype: twilio.rest.proxy.v1.service.session.interaction.InteractionList + :param sid: The Twilio-provided string that uniquely identifies the Session resource to update. """ - return self._proxy.interactions + return SessionContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - @property - def participants(self): + def __call__(self, sid: str) -> SessionContext: """ - Access the participants + Constructs a SessionContext - :returns: twilio.rest.proxy.v1.service.session.participant.ParticipantList - :rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantList + :param sid: The Twilio-provided string that uniquely identifies the Session resource to update. """ - return self._proxy.participants + return SessionContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/proxy/v1/service/session/interaction.py b/twilio/rest/proxy/v1/service/session/interaction.py index 10d3514e2f..7eeccda5bc 100644 --- a/twilio/rest/proxy/v1/service/session/interaction.py +++ b/twilio/rest/proxy/v1/service/session/interaction.py @@ -1,566 +1,571 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 InteractionList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class InteractionInstance(InstanceResource): - def __init__(self, version, service_sid, session_sid): - """ - Initialize the InteractionList + 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" - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param session_sid: Session Sid. + class Type(object): + MESSAGE = "message" + VOICE = "voice" + UNKNOWN = "unknown" - :returns: twilio.rest.proxy.v1.service.session.interaction.InteractionList - :rtype: twilio.rest.proxy.v1.service.session.interaction.InteractionList - """ - super(InteractionList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'service_sid': service_sid, 'session_sid': session_sid, } - self._uri = '/Services/{service_sid}/Sessions/{session_sid}/Interactions'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "session_sid": session_sid, + "sid": sid or self.sid, + } + self._context: Optional[InteractionContext] = None - def stream(self, inbound_participant_status=values.unset, - outbound_participant_status=values.unset, limit=None, - page_size=None): + @property + def _proxy(self) -> "InteractionContext": """ - 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. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param InteractionInstance.ResourceStatus inbound_participant_status: The Inbound Participant Status of this Interaction - :param InteractionInstance.ResourceStatus outbound_participant_status: The Outbound Participant Status of this Interaction - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.proxy.v1.service.session.interaction.InteractionInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the InteractionInstance - page = self.page( - inbound_participant_status=inbound_participant_status, - outbound_participant_status=outbound_participant_status, - page_size=limits['page_size'], - ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, inbound_participant_status=values.unset, - outbound_participant_status=values.unset, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists InteractionInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the InteractionInstance - :param InteractionInstance.ResourceStatus inbound_participant_status: The Inbound Participant Status of this Interaction - :param InteractionInstance.ResourceStatus outbound_participant_status: The Outbound Participant Status of this Interaction - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.proxy.v1.service.session.interaction.InteractionInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream( - inbound_participant_status=inbound_participant_status, - outbound_participant_status=outbound_participant_status, - limit=limit, - page_size=page_size, - )) + return await self._proxy.delete_async() - def page(self, inbound_participant_status=values.unset, - outbound_participant_status=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch(self) -> "InteractionInstance": """ - Retrieve a single page of InteractionInstance records from the API. - Request is executed immediately + Fetch the InteractionInstance - :param InteractionInstance.ResourceStatus inbound_participant_status: The Inbound Participant Status of this Interaction - :param InteractionInstance.ResourceStatus outbound_participant_status: The Outbound Participant Status of this Interaction - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of InteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.interaction.InteractionPage + :returns: The fetched InteractionInstance """ - params = values.of({ - 'InboundParticipantStatus': inbound_participant_status, - 'OutboundParticipantStatus': outbound_participant_status, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + async def fetch_async(self) -> "InteractionInstance": + """ + Asynchronous coroutine to fetch the InteractionInstance - return InteractionPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched InteractionInstance """ - Retrieve a specific page of InteractionInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_async() - :param str target_url: API-generated URL for the requested results page + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of InteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.interaction.InteractionPage + :returns: Machine friendly representation """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - return InteractionPage(self._version, response, self._solution) - def get(self, sid): - """ - Constructs a InteractionContext +class InteractionContext(InstanceContext): - :param sid: A string that uniquely identifies this Interaction. + def __init__(self, version: Version, service_sid: str, session_sid: str, sid: str): + """ + Initialize the InteractionContext - :returns: twilio.rest.proxy.v1.service.session.interaction.InteractionContext - :rtype: twilio.rest.proxy.v1.service.session.interaction.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. """ - return InteractionContext( - self._version, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], - sid=sid, + 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 __call__(self, sid): + def delete(self) -> bool: """ - Constructs a InteractionContext + Deletes the InteractionInstance - :param sid: A string that uniquely identifies this Interaction. - :returns: twilio.rest.proxy.v1.service.session.interaction.InteractionContext - :rtype: twilio.rest.proxy.v1.service.session.interaction.InteractionContext + :returns: True if delete succeeds, False otherwise """ - return InteractionContext( - self._version, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], - sid=sid, - ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the InteractionInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class InteractionPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> InteractionInstance: """ - Initialize the InteractionPage + Fetch the InteractionInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Service Sid. - :param session_sid: Session Sid. - :returns: twilio.rest.proxy.v1.service.session.interaction.InteractionPage - :rtype: twilio.rest.proxy.v1.service.session.interaction.InteractionPage + :returns: The fetched InteractionInstance """ - super(InteractionPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): - """ - Build an instance of InteractionInstance + headers["Accept"] = "application/json" - :param dict payload: Payload response from the API + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.proxy.v1.service.session.interaction.InteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.interaction.InteractionInstance - """ return InteractionInstance( self._version, payload, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + async def fetch_async(self) -> InteractionInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the InteractionInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched InteractionInstance """ - return '' + headers = values.of({}) -class InteractionContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Accept"] = "application/json" - def __init__(self, version, service_sid, session_sid, sid): - """ - Initialize the InteractionContext + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param session_sid: Session Sid. - :param sid: A string that uniquely identifies this Interaction. + return InteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.proxy.v1.service.session.interaction.InteractionContext - :rtype: twilio.rest.proxy.v1.service.session.interaction.InteractionContext + def __repr__(self) -> str: """ - super(InteractionContext, self).__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) + Provide a friendly representation - def fetch(self): + :returns: Machine friendly representation """ - Fetch a InteractionInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: Fetched InteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.interaction.InteractionInstance - """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) +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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], ) - def delete(self): - """ - Deletes the InteractionInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" -class InteractionInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class InteractionList(ListResource): - class Type(object): - MESSAGE = "message" - VOICE = "voice" - UNKNOWN = "unknown" + def __init__(self, version: Version, service_sid: str, session_sid: str): + """ + Initialize the InteractionList - 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" + :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. - def __init__(self, version, payload, service_sid, session_sid, sid=None): - """ - Initialize the InteractionInstance - - :returns: twilio.rest.proxy.v1.service.session.interaction.InteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.interaction.InteractionInstance - """ - super(InteractionInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'session_sid': payload['session_sid'], - 'service_sid': payload['service_sid'], - 'account_sid': payload['account_sid'], - 'data': payload['data'], - 'type': payload['type'], - 'inbound_participant_sid': payload['inbound_participant_sid'], - 'inbound_resource_sid': payload['inbound_resource_sid'], - 'inbound_resource_status': payload['inbound_resource_status'], - 'inbound_resource_type': payload['inbound_resource_type'], - 'inbound_resource_url': payload['inbound_resource_url'], - 'outbound_participant_sid': payload['outbound_participant_sid'], - 'outbound_resource_sid': payload['outbound_resource_sid'], - 'outbound_resource_status': payload['outbound_resource_status'], - 'outbound_resource_type': payload['outbound_resource_type'], - 'outbound_resource_url': payload['outbound_resource_url'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - } + """ + super().__init__(version) - # Context - self._context = None + # Path Solution self._solution = { - 'service_sid': service_sid, - 'session_sid': session_sid, - 'sid': sid or self._properties['sid'], + "service_sid": service_sid, + "session_sid": session_sid, } + self._uri = ( + "/Services/{service_sid}/Sessions/{session_sid}/Interactions".format( + **self._solution + ) + ) - @property - def _proxy(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InteractionInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: InteractionContext for this InteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.interaction.InteractionContext - """ - 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 + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Interaction. - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['sid'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def session_sid(self): - """ - :returns: Session Sid. - :rtype: unicode - """ - return self._properties['session_sid'] + return self._version.stream(page, limits["limit"]) - @property - def service_sid(self): - """ - :returns: Service Sid. - :rtype: unicode + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InteractionInstance]: """ - return self._properties['service_sid'] + 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. - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_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) - @property - def data(self): - """ - :returns: Further details about an interaction. - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['data'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def type(self): - """ - :returns: The Type of this Interaction - :rtype: InteractionInstance.Type - """ - return self._properties['type'] + return self._version.stream_async(page, limits["limit"]) - @property - def inbound_participant_sid(self): + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InteractionInstance]: """ - :returns: Inbound Participant Sid. - :rtype: unicode - """ - return self._properties['inbound_participant_sid'] + Lists InteractionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def inbound_resource_sid(self): - """ - :returns: Inbound Resource Sid. - :rtype: unicode - """ - return self._properties['inbound_resource_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) - @property - def inbound_resource_status(self): - """ - :returns: The Inbound Resource Status of this Interaction - :rtype: InteractionInstance.ResourceStatus + :returns: list that will contain up to limit results """ - return self._properties['inbound_resource_status'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def inbound_resource_type(self): - """ - :returns: The type of the Inbound Resource, Call or Message. - :rtype: unicode + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InteractionInstance]: """ - return self._properties['inbound_resource_type'] + 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. - @property - def inbound_resource_url(self): - """ - :returns: The URL of the Twilio resource. - :rtype: unicode - """ - return self._properties['inbound_resource_url'] + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - @property - def outbound_participant_sid(self): - """ - :returns: Outbound Participant Sid. - :rtype: unicode + :returns: list that will contain up to limit results """ - return self._properties['outbound_participant_sid'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def outbound_resource_sid(self): + 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: """ - :returns: Outbound Resource Sid. - :rtype: unicode - """ - return self._properties['outbound_resource_sid'] + Retrieve a single page of InteractionInstance records from the API. + Request is executed immediately - @property - def outbound_resource_status(self): - """ - :returns: The Outbound Resource Status of this Interaction - :rtype: InteractionInstance.ResourceStatus - """ - return self._properties['outbound_resource_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 - @property - def outbound_resource_type(self): - """ - :returns: The type of the Outbound Resource, Call or Message. - :rtype: unicode + :returns: Page of InteractionInstance """ - return self._properties['outbound_resource_type'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def outbound_resource_url(self): - """ - :returns: The URL of the Twilio resource. - :rtype: unicode - """ - return self._properties['outbound_resource_url'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def date_created(self): + 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: """ - :returns: The date this Interaction was created - :rtype: datetime + 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 """ - return self._properties['date_created'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def date_updated(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The date this Interaction was updated - :rtype: datetime + 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 """ - return self._properties['date_updated'] + response = self._version.domain.twilio.request("GET", target_url) + return InteractionPage(self._version, response, self._solution) - @property - def url(self): + async def get_page_async(self, target_url: str) -> InteractionPage: """ - :returns: The URL of this resource. - :rtype: unicode + 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 """ - return self._properties['url'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return InteractionPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> InteractionContext: """ - Fetch a InteractionInstance + Constructs a InteractionContext - :returns: Fetched InteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.interaction.InteractionInstance + :param sid: The Twilio-provided string that uniquely identifies the Interaction resource to fetch. """ - return self._proxy.fetch() + return InteractionContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=sid, + ) - def delete(self): + def __call__(self, sid: str) -> InteractionContext: """ - Deletes the InteractionInstance + Constructs a InteractionContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the Interaction resource to fetch. """ - return self._proxy.delete() + return InteractionContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/proxy/v1/service/session/participant/__init__.py b/twilio/rest/proxy/v1/service/session/participant/__init__.py index 735671ca57..7ad20fcffb 100644 --- a/twilio/rest/proxy/v1/service/session/participant/__init__.py +++ b/twilio/rest/proxy/v1/service/session/participant/__init__.py @@ -1,585 +1,634 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 +from twilio.rest.proxy.v1.service.session.participant.message_interaction import ( + MessageInteractionList, +) -class ParticipantList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +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 - def __init__(self, version, service_sid, session_sid): + @property + def _proxy(self) -> "ParticipantContext": """ - Initialize the ParticipantList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param session_sid: Session Sid. + :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 - :returns: twilio.rest.proxy.v1.service.session.participant.ParticipantList - :rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantList + def delete(self) -> bool: """ - super(ParticipantList, self).__init__(version) + Deletes the ParticipantInstance - # 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 stream(self, identifier=values.unset, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 unicode identifier: The identifier - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.proxy.v1.service.session.participant.ParticipantInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the ParticipantInstance - page = self.page(identifier=identifier, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, identifier=values.unset, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the ParticipantInstance - :param unicode identifier: The identifier - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.proxy.v1.service.session.participant.ParticipantInstance] + :returns: The fetched ParticipantInstance """ - return list(self.stream(identifier=identifier, limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, identifier=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + async def fetch_async(self) -> "ParticipantInstance": """ - Retrieve a single page of ParticipantInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the ParticipantInstance - :param unicode identifier: The identifier - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of ParticipantInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantPage + :returns: The fetched ParticipantInstance """ - params = values.of({ - 'Identifier': identifier, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return await self._proxy.fetch_async() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + @property + def message_interactions(self) -> MessageInteractionList: + """ + Access the message_interactions + """ + return self._proxy.message_interactions - return ParticipantPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get_page(self, target_url): + :returns: Machine friendly representation """ - Retrieve a specific page of ParticipantInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param str target_url: API-generated URL for the requested results page - :returns: Page of ParticipantInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantPage +class ParticipantContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, session_sid: str, sid: str): """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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 + ) ) - return ParticipantPage(self._version, response, self._solution) + self._message_interactions: Optional[MessageInteractionList] = None - def create(self, identifier, friendly_name=values.unset, - proxy_identifier=values.unset, proxy_identifier_sid=values.unset): + def delete(self) -> bool: """ - Create a new ParticipantInstance + Deletes the ParticipantInstance - :param unicode identifier: The phone number of this Participant. - :param unicode friendly_name: A human readable description of this resource. - :param unicode proxy_identifier: The proxy phone number for this Participant. - :param unicode proxy_identifier_sid: Proxy Identifier Sid. - :returns: Newly created ParticipantInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'Identifier': identifier, - 'FriendlyName': friendly_name, - 'ProxyIdentifier': proxy_identifier, - 'ProxyIdentifierSid': proxy_identifier_sid, - }) - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + headers = values.of({}) - return ParticipantInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], - ) + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def get(self, sid): + async def delete_async(self) -> bool: """ - Constructs a ParticipantContext + Asynchronous coroutine that deletes the ParticipantInstance - :param sid: A string that uniquely identifies this Participant. - :returns: twilio.rest.proxy.v1.service.session.participant.ParticipantContext - :rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantContext + :returns: True if delete succeeds, False otherwise """ - return ParticipantContext( - self._version, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], - sid=sid, + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers ) - def __call__(self, sid): + def fetch(self) -> ParticipantInstance: """ - Constructs a ParticipantContext + Fetch the ParticipantInstance - :param sid: A string that uniquely identifies this Participant. - :returns: twilio.rest.proxy.v1.service.session.participant.ParticipantContext - :rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantContext + :returns: The fetched ParticipantInstance """ - return ParticipantContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ParticipantInstance( self._version, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + async def fetch_async(self) -> ParticipantInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the ParticipantInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched ParticipantInstance """ - return '' + headers = values.of({}) -class ParticipantPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + 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 """ - Initialize the ParticipantPage + 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 - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Service Sid. - :param session_sid: Session Sid. + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.proxy.v1.service.session.participant.ParticipantPage - :rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantPage + :returns: Machine friendly representation """ - super(ParticipantPage, self).__init__(version, response) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Path Solution - self._solution = solution - def get_instance(self, payload): +class ParticipantPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: """ Build an instance of ParticipantInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.proxy.v1.service.session.participant.ParticipantInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.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'], + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class ParticipantContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class ParticipantList(ListResource): - def __init__(self, version, service_sid, session_sid, sid): + def __init__(self, version: Version, service_sid: str, session_sid: str): """ - Initialize the ParticipantContext + Initialize the ParticipantList - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param session_sid: Session Sid. - :param sid: A string that uniquely identifies this Participant. + :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. - :returns: twilio.rest.proxy.v1.service.session.participant.ParticipantContext - :rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantContext """ - super(ParticipantContext, self).__init__(version) + 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) - - # Dependents - self._message_interactions = None + self._solution = { + "service_sid": service_sid, + "session_sid": session_sid, + } + self._uri = ( + "/Services/{service_sid}/Sessions/{session_sid}/Participants".format( + **self._solution + ) + ) - def fetch(self): + 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: """ - Fetch a 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: Fetched ParticipantInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantInstance + :returns: The created ParticipantInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], ) - def delete(self): + 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: """ - Deletes the ParticipantInstance + Asynchronously create the ParticipantInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :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. - def update(self, identifier=values.unset, friendly_name=values.unset, - proxy_identifier=values.unset, proxy_identifier_sid=values.unset): + :returns: The created ParticipantInstance """ - Update the ParticipantInstance - :param unicode identifier: The phone number of this Participant. - :param unicode friendly_name: A human readable description of this resource. - :param unicode proxy_identifier: The proxy phone number for this Participant. - :param unicode proxy_identifier_sid: Proxy Identifier Sid. + 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" - :returns: Updated ParticipantInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantInstance - """ - data = values.of({ - 'Identifier': identifier, - 'FriendlyName': friendly_name, - 'ProxyIdentifier': proxy_identifier, - 'ProxyIdentifierSid': proxy_identifier_sid, - }) + headers["Accept"] = "application/json" - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], ) - @property - def message_interactions(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ParticipantInstance]: """ - Access the message_interactions + 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. - :returns: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList - :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList - """ - if self._message_interactions is None: - self._message_interactions = MessageInteractionList( - self._version, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], - participant_sid=self._solution['sid'], - ) - return self._message_interactions + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - def __repr__(self): + :returns: Generator that will yield up to limit results """ - Provide a friendly representation + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - :returns: Machine friendly representation - :rtype: str + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ParticipantInstance]: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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) -class ParticipantInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, payload, service_sid, session_sid, sid=None): - """ - Initialize the ParticipantInstance - - :returns: twilio.rest.proxy.v1.service.session.participant.ParticipantInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantInstance - """ - super(ParticipantInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'session_sid': payload['session_sid'], - 'service_sid': payload['service_sid'], - 'account_sid': payload['account_sid'], - 'friendly_name': payload['friendly_name'], - 'identifier': payload['identifier'], - 'proxy_identifier': payload['proxy_identifier'], - 'proxy_identifier_sid': payload['proxy_identifier_sid'], - 'date_deleted': deserialize.iso8601_datetime(payload['date_deleted']), - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - 'links': payload['links'], - } + :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"]) - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'session_sid': session_sid, - 'sid': sid or self._properties['sid'], - } + return self._version.stream_async(page, limits["limit"]) - @property - def _proxy(self): + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: ParticipantContext for this ParticipantInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantContext + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - 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 list( + self.stream( + limit=limit, + page_size=page_size, ) - return self._context + ) - @property - def sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: """ - :returns: A string that uniquely identifies this Participant. - :rtype: unicode - """ - return self._properties['sid'] + 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. - @property - def session_sid(self): - """ - :returns: Session Sid. - :rtype: unicode - """ - return self._properties['session_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) - @property - def service_sid(self): - """ - :returns: Service Sid. - :rtype: unicode + :returns: list that will contain up to limit results """ - return self._properties['service_sid'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def account_sid(self): + 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: """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] + Retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately - @property - def friendly_name(self): - """ - :returns: A human readable description of this resource. - :rtype: unicode - """ - return self._properties['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 - @property - def identifier(self): - """ - :returns: The phone number of this Participant. - :rtype: unicode + :returns: Page of ParticipantInstance """ - return self._properties['identifier'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def proxy_identifier(self): - """ - :returns: The proxy_identifier - :rtype: unicode - """ - return self._properties['proxy_identifier'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def proxy_identifier_sid(self): - """ - :returns: Proxy Identifier Sid. - :rtype: unicode - """ - return self._properties['proxy_identifier_sid'] + headers["Accept"] = "application/json" - @property - def date_deleted(self): - """ - :returns: The date this Participant was deleted - :rtype: datetime - """ - return self._properties['date_deleted'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) - @property - def date_created(self): + 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: """ - :returns: The date this Participant was created - :rtype: datetime - """ - return self._properties['date_created'] + Asynchronously retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately - @property - def date_updated(self): - """ - :returns: The date this Participant was updated - :rtype: datetime - """ - return self._properties['date_updated'] + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - @property - def url(self): - """ - :returns: The URL of this resource. - :rtype: unicode + :returns: Page of ParticipantInstance """ - return self._properties['url'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def links(self): - """ - :returns: Nested resource URLs. - :rtype: unicode - """ - return self._properties['links'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def fetch(self): - """ - Fetch a ParticipantInstance + 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) - :returns: Fetched ParticipantInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantInstance + def get_page(self, target_url: str) -> ParticipantPage: """ - return self._proxy.fetch() + Retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately - def delete(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance """ - Deletes the ParticipantInstance + response = self._version.domain.twilio.request("GET", target_url) + return ParticipantPage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def get_page_async(self, target_url: str) -> ParticipantPage: """ - return self._proxy.delete() + 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 - def update(self, identifier=values.unset, friendly_name=values.unset, - proxy_identifier=values.unset, proxy_identifier_sid=values.unset): + :returns: Page of ParticipantInstance """ - Update the ParticipantInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return ParticipantPage(self._version, response, self._solution) - :param unicode identifier: The phone number of this Participant. - :param unicode friendly_name: A human readable description of this resource. - :param unicode proxy_identifier: The proxy phone number for this Participant. - :param unicode proxy_identifier_sid: Proxy Identifier Sid. + def get(self, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext - :returns: Updated ParticipantInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantInstance + :param sid: The Twilio-provided string that uniquely identifies the Participant resource to fetch. """ - return self._proxy.update( - identifier=identifier, - friendly_name=friendly_name, - proxy_identifier=proxy_identifier, - proxy_identifier_sid=proxy_identifier_sid, + return ParticipantContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=sid, ) - @property - def message_interactions(self): + def __call__(self, sid: str) -> ParticipantContext: """ - Access the message_interactions + Constructs a ParticipantContext - :returns: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList - :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList + :param sid: The Twilio-provided string that uniquely identifies the Participant resource to fetch. """ - return self._proxy.message_interactions + return ParticipantContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/proxy/v1/service/session/participant/message_interaction.py b/twilio/rest/proxy/v1/service/session/participant/message_interaction.py index 15b2ee5b75..4ffe67965b 100644 --- a/twilio/rest/proxy/v1/service/session/participant/message_interaction.py +++ b/twilio/rest/proxy/v1/service/session/participant/message_interaction.py @@ -1,578 +1,622 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 MessageInteractionList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class MessageInteractionInstance(InstanceResource): - def __init__(self, version, service_sid, session_sid, participant_sid): - """ - Initialize the MessageInteractionList + 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" - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param session_sid: Session Sid. - :param participant_sid: Participant Sid. + class Type(object): + MESSAGE = "message" + VOICE = "voice" + UNKNOWN = "unknown" - :returns: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList - :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList - """ - super(MessageInteractionList, self).__init__(version) + """ + :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") - # Path Solution self._solution = { - 'service_sid': service_sid, - 'session_sid': session_sid, - 'participant_sid': participant_sid, + "service_sid": service_sid, + "session_sid": session_sid, + "participant_sid": participant_sid, + "sid": sid or self.sid, } - self._uri = '/Services/{service_sid}/Sessions/{session_sid}/Participants/{participant_sid}/MessageInteractions'.format(**self._solution) + self._context: Optional[MessageInteractionContext] = None - def create(self, body=values.unset, media_url=values.unset): + @property + def _proxy(self) -> "MessageInteractionContext": """ - Create a new MessageInteractionInstance + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param unicode body: The body - :param unicode media_url: The media_url + :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 - :returns: Newly created MessageInteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionInstance + def fetch(self) -> "MessageInteractionInstance": """ - data = values.of({'Body': body, 'MediaUrl': serialize.map(media_url, lambda e: e), }) + Fetch the MessageInteractionInstance - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - return MessageInteractionInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], - participant_sid=self._solution['participant_sid'], - ) + :returns: The fetched MessageInteractionInstance + """ + return self._proxy.fetch() - def stream(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the MessageInteractionInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionInstance] + :returns: The fetched MessageInteractionInstance """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.fetch_async() - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) + def __repr__(self) -> str: + """ + Provide a friendly representation - def list(self, limit=None, page_size=None): + :returns: Machine friendly representation """ - Lists MessageInteractionInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) +class MessageInteractionContext(InstanceContext): - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def __init__( + self, + version: Version, + service_sid: str, + session_sid: str, + participant_sid: str, + sid: str, + ): """ - Retrieve a single page of MessageInteractionInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + Initialize the MessageInteractionContext - :returns: Page of MessageInteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionPage + :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. """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + super().__init__(version) - response = self._version.page( - 'GET', - self._uri, - params=params, + # 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 ) - return MessageInteractionPage(self._version, response, self._solution) - - def get_page(self, target_url): + def fetch(self) -> MessageInteractionInstance: """ - Retrieve a specific page of MessageInteractionInstance records from the API. - Request is executed immediately + Fetch the MessageInteractionInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of MessageInteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionPage + :returns: The fetched MessageInteractionInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return MessageInteractionPage(self._version, response, self._solution) + headers = values.of({}) - def get(self, sid): - """ - Constructs a MessageInteractionContext + headers["Accept"] = "application/json" - :param sid: A string that uniquely identifies this Message Interaction. + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionContext - :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionContext - """ - return MessageInteractionContext( + return MessageInteractionInstance( self._version, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], - participant_sid=self._solution['participant_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], ) - def __call__(self, sid): + async def fetch_async(self) -> MessageInteractionInstance: """ - Constructs a MessageInteractionContext + Asynchronous coroutine to fetch the MessageInteractionInstance - :param sid: A string that uniquely identifies this Message Interaction. - :returns: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionContext - :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionContext + :returns: The fetched MessageInteractionInstance """ - return MessageInteractionContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MessageInteractionInstance( self._version, - service_sid=self._solution['service_sid'], - session_sid=self._solution['session_sid'], - participant_sid=self._solution['participant_sid'], - sid=sid, + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) class MessageInteractionPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - def __init__(self, version, response, solution): - """ - Initialize the MessageInteractionPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Service Sid. - :param session_sid: Session Sid. - :param participant_sid: Participant Sid. - - :returns: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionPage - :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionPage - """ - super(MessageInteractionPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): + def get_instance(self, payload: Dict[str, Any]) -> MessageInteractionInstance: """ Build an instance of MessageInteractionInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.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'], + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class MessageInteractionContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class MessageInteractionList(ListResource): - def __init__(self, version, service_sid, session_sid, participant_sid, sid): + def __init__( + self, version: Version, service_sid: str, session_sid: str, participant_sid: str + ): """ - Initialize the MessageInteractionContext + Initialize the MessageInteractionList - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param session_sid: Session Sid. - :param participant_sid: Participant Sid. - :param sid: A string that uniquely identifies this Message Interaction. + :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. - :returns: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionContext - :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionContext """ - super(MessageInteractionContext, self).__init__(version) + super().__init__(version) # Path Solution self._solution = { - 'service_sid': service_sid, - 'session_sid': session_sid, - 'participant_sid': participant_sid, - 'sid': sid, + "service_sid": service_sid, + "session_sid": session_sid, + "participant_sid": participant_sid, } - self._uri = '/Services/{service_sid}/Sessions/{session_sid}/Participants/{participant_sid}/MessageInteractions/{sid}'.format(**self._solution) + self._uri = "/Services/{service_sid}/Sessions/{session_sid}/Participants/{participant_sid}/MessageInteractions".format( + **self._solution + ) - def fetch(self): + def create( + self, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + ) -> MessageInteractionInstance: """ - Fetch a MessageInteractionInstance + Create the MessageInteractionInstance - :returns: Fetched MessageInteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionInstance + :param body: The message to send to the participant + :param media_url: Reserved. Not currently supported. + + :returns: The created MessageInteractionInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], ) - def __repr__(self): + async def create_async( + self, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + ) -> MessageInteractionInstance: """ - Provide a friendly representation + Asynchronously create the MessageInteractionInstance - :returns: Machine friendly representation - :rtype: str + :param body: The message to send to the participant + :param media_url: Reserved. Not currently supported. + + :returns: The created MessageInteractionInstance """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + data = values.of( + { + "Body": body, + "MediaUrl": serialize.map(media_url, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) -class MessageInteractionInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - class Type(object): - MESSAGE = "message" - VOICE = "voice" - UNKNOWN = "unknown" - - 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" + headers["Accept"] = "application/json" - def __init__(self, version, payload, service_sid, session_sid, participant_sid, - sid=None): - """ - Initialize the MessageInteractionInstance - - :returns: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionInstance - """ - super(MessageInteractionInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'session_sid': payload['session_sid'], - 'service_sid': payload['service_sid'], - 'account_sid': payload['account_sid'], - 'data': payload['data'], - 'type': payload['type'], - 'participant_sid': payload['participant_sid'], - 'inbound_participant_sid': payload['inbound_participant_sid'], - 'inbound_resource_sid': payload['inbound_resource_sid'], - 'inbound_resource_status': payload['inbound_resource_status'], - 'inbound_resource_type': payload['inbound_resource_type'], - 'inbound_resource_url': payload['inbound_resource_url'], - 'outbound_participant_sid': payload['outbound_participant_sid'], - 'outbound_resource_sid': payload['outbound_resource_sid'], - 'outbound_resource_status': payload['outbound_resource_status'], - 'outbound_resource_type': payload['outbound_resource_type'], - 'outbound_resource_url': payload['outbound_resource_url'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - } + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'session_sid': session_sid, - 'participant_sid': participant_sid, - 'sid': sid or self._properties['sid'], - } + return MessageInteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + ) - @property - def _proxy(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInteractionInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: MessageInteractionContext for this MessageInteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionContext - """ - 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 + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Message Interaction. - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['sid'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def session_sid(self): - """ - :returns: Session Sid. - :rtype: unicode - """ - return self._properties['session_sid'] + return self._version.stream(page, limits["limit"]) - @property - def service_sid(self): + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessageInteractionInstance]: """ - :returns: Service Sid. - :rtype: unicode - """ - return self._properties['service_sid'] + 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. - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_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) - @property - def data(self): - """ - :returns: Further details about an interaction. - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['data'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def type(self): - """ - :returns: The Type of this Message Interaction - :rtype: MessageInteractionInstance.Type - """ - return self._properties['type'] + return self._version.stream_async(page, limits["limit"]) - @property - def participant_sid(self): + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInteractionInstance]: """ - :returns: Participant Sid. - :rtype: unicode - """ - return self._properties['participant_sid'] + Lists MessageInteractionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def inbound_participant_sid(self): - """ - :returns: Inbound Participant Sid. - :rtype: unicode - """ - return self._properties['inbound_participant_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) - @property - def inbound_resource_sid(self): + :returns: list that will contain up to limit results """ - :returns: Inbound Resource Sid. - :rtype: unicode - """ - return self._properties['inbound_resource_sid'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def inbound_resource_status(self): - """ - :returns: The Inbound Resource Status of this Message Interaction - :rtype: MessageInteractionInstance.ResourceStatus + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInteractionInstance]: """ - return self._properties['inbound_resource_status'] + 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. - @property - def inbound_resource_type(self): - """ - :returns: The type of the Inbound Resource, Call or Message. - :rtype: unicode - """ - return self._properties['inbound_resource_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) - @property - def inbound_resource_url(self): - """ - :returns: The URL of the Twilio resource. - :rtype: unicode + :returns: list that will contain up to limit results """ - return self._properties['inbound_resource_url'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def outbound_participant_sid(self): + 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: """ - :returns: Outbound Participant Sid. - :rtype: unicode - """ - return self._properties['outbound_participant_sid'] + Retrieve a single page of MessageInteractionInstance records from the API. + Request is executed immediately - @property - def outbound_resource_sid(self): - """ - :returns: Outbound Resource Sid. - :rtype: unicode - """ - return self._properties['outbound_resource_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 - @property - def outbound_resource_status(self): - """ - :returns: The Outbound Resource Status of this Message Interaction - :rtype: MessageInteractionInstance.ResourceStatus + :returns: Page of MessageInteractionInstance """ - return self._properties['outbound_resource_status'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def outbound_resource_type(self): - """ - :returns: The type of the Outbound Resource, Call or Message. - :rtype: unicode - """ - return self._properties['outbound_resource_type'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def outbound_resource_url(self): + 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: """ - :returns: The URL of the Twilio resource. - :rtype: unicode + 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 """ - return self._properties['outbound_resource_url'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def date_created(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The date this Message Interaction was created - :rtype: datetime + 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 """ - return self._properties['date_created'] + response = self._version.domain.twilio.request("GET", target_url) + return MessageInteractionPage(self._version, response, self._solution) - @property - def date_updated(self): + async def get_page_async(self, target_url: str) -> MessageInteractionPage: """ - :returns: The date this Message Interaction was updated - :rtype: datetime + 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 """ - return self._properties['date_updated'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessageInteractionPage(self._version, response, self._solution) - @property - def url(self): + def get(self, sid: str) -> MessageInteractionContext: """ - :returns: The URL of this resource. - :rtype: unicode + Constructs a MessageInteractionContext + + :param sid: The Twilio-provided string that uniquely identifies the MessageInteraction resource to fetch. """ - return self._properties['url'] + 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 fetch(self): + def __call__(self, sid: str) -> MessageInteractionContext: """ - Fetch a MessageInteractionInstance + Constructs a MessageInteractionContext - :returns: Fetched MessageInteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionInstance + :param sid: The Twilio-provided string that uniquely identifies the MessageInteraction resource to fetch. """ - return self._proxy.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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/proxy/v1/service/short_code.py b/twilio/rest/proxy/v1/service/short_code.py index 7c32034953..df71d4bdd5 100644 --- a/twilio/rest/proxy/v1/service/short_code.py +++ b/twilio/rest/proxy/v1/service/short_code.py @@ -1,418 +1,638 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 ShortCodeList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +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 - def __init__(self, version, service_sid): + @property + def _proxy(self) -> "ShortCodeContext": """ - Initialize the ShortCodeList - - :param Version version: Version that contains the resource - :param service_sid: Service Sid. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: twilio.rest.proxy.v1.service.short_code.ShortCodeList - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeList + :returns: ShortCodeContext for this ShortCodeInstance """ - super(ShortCodeList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/ShortCodes'.format(**self._solution) + if self._context is None: + self._context = ShortCodeContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - def create(self, sid): + def delete(self) -> bool: """ - Create a new ShortCodeInstance + Deletes the ShortCodeInstance - :param unicode sid: A string that uniquely identifies this Short Code. - :returns: Newly created ShortCodeInstance - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({'Sid': sid, }) + return self._proxy.delete() - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ShortCodeInstance - return ShortCodeInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return await self._proxy.delete_async() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.proxy.v1.service.short_code.ShortCodeInstance] + def fetch(self) -> "ShortCodeInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the ShortCodeInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched ShortCodeInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the ShortCodeInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.proxy.v1.service.short_code.ShortCodeInstance] + :returns: The fetched ShortCodeInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def update( + self, is_reserved: Union[bool, object] = values.unset + ) -> "ShortCodeInstance": """ - Retrieve a single page of ShortCodeInstance records from the API. - Request is executed immediately + Update the ShortCodeInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :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: Page of ShortCodeInstance - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodePage + :returns: The updated ShortCodeInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + return self._proxy.update( + is_reserved=is_reserved, ) - return ShortCodePage(self._version, response, self._solution) - - def get_page(self, target_url): + async def update_async( + self, is_reserved: Union[bool, object] = values.unset + ) -> "ShortCodeInstance": """ - Retrieve a specific page of ShortCodeInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the ShortCodeInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of ShortCodeInstance - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodePage + :returns: The updated ShortCodeInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + is_reserved=is_reserved, ) - return ShortCodePage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a ShortCodeContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param sid: A string that uniquely identifies this Short Code. - :returns: twilio.rest.proxy.v1.service.short_code.ShortCodeContext - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeContext +class ShortCodeContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): """ - return ShortCodeContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Initialize the ShortCodeContext - def __call__(self, sid): + :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. """ - Constructs a ShortCodeContext + super().__init__(version) - :param sid: A string that uniquely identifies this Short Code. + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/ShortCodes/{sid}".format(**self._solution) - :returns: twilio.rest.proxy.v1.service.short_code.ShortCodeContext - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeContext + def delete(self) -> bool: """ - return ShortCodeContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Deletes the ShortCodeInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class ShortCodePage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, response, solution): + async def delete_async(self) -> bool: """ - Initialize the ShortCodePage + Asynchronous coroutine that deletes the ShortCodeInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Service Sid. - :returns: twilio.rest.proxy.v1.service.short_code.ShortCodePage - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodePage + :returns: True if delete succeeds, False otherwise """ - super(ShortCodePage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ShortCodeInstance: """ - Build an instance of ShortCodeInstance + Fetch the ShortCodeInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance + :returns: The fetched ShortCodeInstance """ - return ShortCodeInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def __repr__(self): - """ - Provide a friendly representation + headers = values.of({}) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Accept"] = "application/json" + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) -class ShortCodeContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return ShortCodeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - def __init__(self, version, service_sid, sid): + async def fetch_async(self) -> ShortCodeInstance: """ - Initialize the ShortCodeContext + Asynchronous coroutine to fetch the ShortCodeInstance - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param sid: A string that uniquely identifies this Short Code. - :returns: twilio.rest.proxy.v1.service.short_code.ShortCodeContext - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeContext + :returns: The fetched ShortCodeInstance """ - super(ShortCodeContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/ShortCodes/{sid}'.format(**self._solution) + headers = values.of({}) - def delete(self): + 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: """ - Deletes the ShortCodeInstance + Update the ShortCodeInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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._version.delete('delete', self._uri) - def fetch(self): + 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: """ - Fetch a 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: Fetched ShortCodeInstance - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance + :returns: The updated ShortCodeInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ShortCodeInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class ShortCodePage(Page): - def __init__(self, version, payload, service_sid, sid=None): + def get_instance(self, payload: Dict[str, Any]) -> ShortCodeInstance: """ - Initialize the ShortCodeInstance + Build an instance of ShortCodeInstance - :returns: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance + :param payload: Payload response from the API """ - super(ShortCodeInstance, self).__init__(version) + return ShortCodeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'short_code': payload['short_code'], - 'iso_country': payload['iso_country'], - 'capabilities': payload['capabilities'], - 'url': payload['url'], - } + def __repr__(self) -> str: + """ + Provide a friendly representation - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + :returns: Machine friendly representation + """ + return "" - @property - def _proxy(self): + +class ShortCodeList(ListResource): + + def __init__(self, version: Version, service_sid: str): """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: ShortCodeContext for this ShortCodeInstance - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeContext """ - if self._context is None: - self._context = ShortCodeContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + super().__init__(version) - @property - def sid(self): + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/ShortCodes".format(**self._solution) + + def create(self, sid: str) -> ShortCodeInstance: """ - :returns: A string that uniquely identifies this Short Code. - :rtype: unicode + 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 """ - return self._properties['sid'] - @property - def account_sid(self): + 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: """ - :returns: Account Sid. - :rtype: unicode + 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 """ - return self._properties['account_sid'] - @property - def service_sid(self): + 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]: """ - :returns: Service Sid. - :rtype: unicode + 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 """ - return self._properties['service_sid'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def date_created(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ShortCodeInstance]: """ - :returns: The date this Short Code was created - :rtype: datetime + 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 """ - return self._properties['date_created'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def date_updated(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ShortCodeInstance]: """ - :returns: The date this Short Code was updated - :rtype: datetime + 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 self._properties['date_updated'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def short_code(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ShortCodeInstance]: """ - :returns: Shortcode. - :rtype: unicode + 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 self._properties['short_code'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def iso_country(self): + 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: """ - :returns: ISO Country Code, - :rtype: unicode + 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 """ - return self._properties['iso_country'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def capabilities(self): + headers = values.of({"Content-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: """ - :returns: Nested resource URLs. - :rtype: unicode + 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 """ - return self._properties['capabilities'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def url(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The URL of this resource. - :rtype: unicode + 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 """ - return self._properties['url'] + response = self._version.domain.twilio.request("GET", target_url) + return ShortCodePage(self._version, response, self._solution) - def delete(self): + async def get_page_async(self, target_url: str) -> ShortCodePage: """ - Deletes the ShortCodeInstance + Asynchronously retrieve a specific page of ShortCodeInstance records from the API. + Request is executed immediately - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param target_url: API-generated URL for the requested results page + + :returns: Page of ShortCodeInstance """ - return self._proxy.delete() + response = await self._version.domain.twilio.request_async("GET", target_url) + return ShortCodePage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> ShortCodeContext: """ - Fetch a ShortCodeInstance + Constructs a ShortCodeContext - :returns: Fetched ShortCodeInstance - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance + :param sid: The Twilio-provided string that uniquely identifies the ShortCode resource to update. """ - return self._proxy.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 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 "" 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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" 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 "" 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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 ''.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 ''.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 "" + + + + + +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 '' + 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 ''.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 ''.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 '' + 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" 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 "" diff --git a/twilio/rest/studio/__init__.py b/twilio/rest/studio/__init__.py index a9abc21171..986e694221 100644 --- a/twilio/rest/studio/__init__.py +++ b/twilio/rest/studio/__init__.py @@ -1,53 +1,25 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" +from warnings import warn -from twilio.base.domain import Domain -from twilio.rest.studio.v1 import V1 +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(Domain): - - def __init__(self, twilio): - """ - Initialize the Studio Domain - - :returns: Domain for Studio - :rtype: twilio.rest.studio.Studio - """ - super(Studio, self).__init__(twilio) - - self.base_url = 'https://studio.twilio.com' - - # Versions - self._v1 = None - +class Studio(StudioBase): @property - def v1(self): - """ - :returns: Version v1 of studio - :rtype: twilio.rest.studio.v1.V1 - """ - if self._v1 is None: - self._v1 = V1(self) - return self._v1 + def flows(self) -> FlowList: + warn( + "flows is deprecated. Use v2.flows instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.flows @property - def flows(self): - """ - :rtype: twilio.rest.studio.v1.flow.FlowList - """ - return self.v1.flows - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' + 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 index 41c0b254c1..8ab7d71b6c 100644 --- a/twilio/rest/studio/v1/__init__.py +++ b/twilio/rest/studio/v1/__init__.py @@ -1,42 +1,43 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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): + def __init__(self, domain: Domain): """ Initialize the V1 version of Studio - :returns: V1 version of Studio - :rtype: twilio.rest.studio.v1.V1.V1 + :param domain: The Twilio.studio domain """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._flows = None + super().__init__(domain, "v1") + self._flows: Optional[FlowList] = None @property - def flows(self): - """ - :rtype: twilio.rest.studio.v1.flow.FlowList - """ + def flows(self) -> FlowList: if self._flows is None: self._flows = FlowList(self) return self._flows - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/studio/v1/flow/__init__.py b/twilio/rest/studio/v1/flow/__init__.py index b390e092d3..533c1a45f5 100644 --- a/twilio/rest/studio/v1/flow/__init__.py +++ b/twilio/rest/studio/v1/flow/__init__.py @@ -1,417 +1,513 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 FlowList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version): - """ - Initialize the FlowList +class FlowInstance(InstanceResource): - :param Version version: Version that contains the resource + class Status(object): + DRAFT = "draft" + PUBLISHED = "published" - :returns: twilio.rest.studio.v1.flow.FlowList - :rtype: twilio.rest.studio.v1.flow.FlowList - """ - super(FlowList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {} - self._uri = '/Flows'.format(**self._solution) + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[FlowContext] = None - def stream(self, limit=None, page_size=None): + @property + def _proxy(self) -> "FlowContext": """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.studio.v1.flow.FlowInstance] + :returns: FlowContext for this FlowInstance """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) + if self._context is None: + self._context = FlowContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def list(self, limit=None, page_size=None): + def delete(self) -> bool: """ - Lists FlowInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the FlowInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.studio.v1.flow.FlowInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.delete() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def delete_async(self) -> bool: """ - Retrieve a single page of FlowInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the FlowInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of FlowInstance - :rtype: twilio.rest.studio.v1.flow.FlowPage + :returns: True if delete succeeds, False otherwise """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + return await self._proxy.delete_async() - return FlowPage(self._version, response, self._solution) - - def get_page(self, target_url): + def fetch(self) -> "FlowInstance": """ - Retrieve a specific page of FlowInstance records from the API. - Request is executed immediately + Fetch the FlowInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of FlowInstance - :rtype: twilio.rest.studio.v1.flow.FlowPage + :returns: The fetched FlowInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return FlowPage(self._version, response, self._solution) + return self._proxy.fetch() - def get(self, sid): + async def fetch_async(self) -> "FlowInstance": """ - Constructs a FlowContext + Asynchronous coroutine to fetch the FlowInstance - :param sid: The sid - :returns: twilio.rest.studio.v1.flow.FlowContext - :rtype: twilio.rest.studio.v1.flow.FlowContext + :returns: The fetched FlowInstance """ - return FlowContext(self._version, sid=sid, ) + return await self._proxy.fetch_async() - def __call__(self, sid): + @property + def engagements(self) -> EngagementList: """ - Constructs a FlowContext - - :param sid: The sid + Access the engagements + """ + return self._proxy.engagements - :returns: twilio.rest.studio.v1.flow.FlowContext - :rtype: twilio.rest.studio.v1.flow.FlowContext + @property + def executions(self) -> ExecutionList: + """ + Access the executions """ - return FlowContext(self._version, sid=sid, ) + return self._proxy.executions - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class FlowPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class FlowContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the FlowPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the FlowContext - :returns: twilio.rest.studio.v1.flow.FlowPage - :rtype: twilio.rest.studio.v1.flow.FlowPage + :param version: Version that contains the resource + :param sid: The SID of the Flow resource to fetch. """ - super(FlowPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/Flows/{sid}".format(**self._solution) + + self._engagements: Optional[EngagementList] = None + self._executions: Optional[ExecutionList] = None - def get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of FlowInstance + Deletes the FlowInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.studio.v1.flow.FlowInstance - :rtype: twilio.rest.studio.v1.flow.FlowInstance + :returns: True if delete succeeds, False otherwise """ - return FlowInstance(self._version, payload, ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the FlowInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class FlowContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, sid): + def fetch(self) -> FlowInstance: """ - Initialize the FlowContext + Fetch the FlowInstance - :param Version version: Version that contains the resource - :param sid: The sid - :returns: twilio.rest.studio.v1.flow.FlowContext - :rtype: twilio.rest.studio.v1.flow.FlowContext + :returns: The fetched FlowInstance """ - super(FlowContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Flows/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._engagements = None + headers["Accept"] = "application/json" - def fetch(self): + 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: """ - Fetch a FlowInstance + Asynchronous coroutine to fetch the FlowInstance - :returns: Fetched FlowInstance - :rtype: twilio.rest.studio.v1.flow.FlowInstance + + :returns: The fetched FlowInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) + headers = values.of({}) - return FlowInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" - def delete(self): - """ - Deletes the FlowInstance + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + return FlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) @property - def engagements(self): + def engagements(self) -> EngagementList: """ Access the engagements - - :returns: twilio.rest.studio.v1.flow.engagement.EngagementList - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementList """ if self._engagements is None: - self._engagements = EngagementList(self._version, flow_sid=self._solution['sid'], ) + self._engagements = EngagementList( + self._version, + self._solution["sid"], + ) return self._engagements - def __repr__(self): + @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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class FlowInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class FlowPage(Page): - class Status(object): - DRAFT = "draft" - PUBLISHED = "published" + def get_instance(self, payload: Dict[str, Any]) -> FlowInstance: + """ + Build an instance of FlowInstance - def __init__(self, version, payload, sid=None): + :param payload: Payload response from the API """ - Initialize the FlowInstance + return FlowInstance(self._version, payload) - :returns: twilio.rest.studio.v1.flow.FlowInstance - :rtype: twilio.rest.studio.v1.flow.FlowInstance + def __repr__(self) -> str: """ - super(FlowInstance, self).__init__(version) + Provide a friendly representation - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'friendly_name': payload['friendly_name'], - 'status': payload['status'], - 'version': deserialize.integer(payload['version']), - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - 'links': payload['links'], - } + :returns: Machine friendly representation + """ + return "" - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context +class FlowList(ListResource): - :returns: FlowContext for this FlowInstance - :rtype: twilio.rest.studio.v1.flow.FlowContext + def __init__(self, version: Version): """ - if self._context is None: - self._context = FlowContext(self._version, sid=self._solution['sid'], ) - return self._context + Initialize the FlowList - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + :param version: Version that contains the resource - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode """ - return self._properties['account_sid'] + super().__init__(version) - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode + self._uri = "/Flows" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FlowInstance]: """ - return self._properties['friendly_name'] + 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. - @property - def status(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The status - :rtype: FlowInstance.Status + 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]: """ - return self._properties['status'] + 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. - @property - def version(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The version - :rtype: unicode + 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]: """ - return self._properties['version'] + Lists FlowInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def date_created(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The date_created - :rtype: datetime + 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]: """ - return self._properties['date_created'] + 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. - @property - def date_updated(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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: """ - :returns: The date_updated - :rtype: datetime + 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 """ - return self._properties['date_updated'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def url(self): + headers = values.of({"Content-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: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def links(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The links - :rtype: unicode + 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 """ - return self._properties['links'] + response = self._version.domain.twilio.request("GET", target_url) + return FlowPage(self._version, response) - def fetch(self): + async def get_page_async(self, target_url: str) -> FlowPage: """ - Fetch a FlowInstance + Asynchronously retrieve a specific page of FlowInstance records from the API. + Request is executed immediately - :returns: Fetched FlowInstance - :rtype: twilio.rest.studio.v1.flow.FlowInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of FlowInstance """ - return self._proxy.fetch() + response = await self._version.domain.twilio.request_async("GET", target_url) + return FlowPage(self._version, response) - def delete(self): + def get(self, sid: str) -> FlowContext: """ - Deletes the FlowInstance + Constructs a FlowContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The SID of the Flow resource to fetch. """ - return self._proxy.delete() + return FlowContext(self._version, sid=sid) - @property - def engagements(self): + def __call__(self, sid: str) -> FlowContext: """ - Access the engagements + Constructs a FlowContext - :returns: twilio.rest.studio.v1.flow.engagement.EngagementList - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementList + :param sid: The SID of the Flow resource to fetch. """ - return self._proxy.engagements + return FlowContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/studio/v1/flow/engagement/__init__.py b/twilio/rest/studio/v1/flow/engagement/__init__.py index fc124bb930..759d92506c 100644 --- a/twilio/rest/studio/v1/flow/engagement/__init__.py +++ b/twilio/rest/studio/v1/flow/engagement/__init__.py @@ -1,483 +1,612 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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.engagement_context import ( + EngagementContextList, +) from twilio.rest.studio.v1.flow.engagement.step import StepList -class EngagementList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, flow_sid): - """ - Initialize the EngagementList +class EngagementInstance(InstanceResource): - :param Version version: Version that contains the resource - :param flow_sid: The flow_sid + class Status(object): + ACTIVE = "active" + ENDED = "ended" - :returns: twilio.rest.studio.v1.flow.engagement.EngagementList - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementList - """ - super(EngagementList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'flow_sid': flow_sid, } - self._uri = '/Flows/{flow_sid}/Engagements'.format(**self._solution) + self._solution = { + "flow_sid": flow_sid, + "sid": sid or self.sid, + } + self._context: Optional[EngagementContext] = None - def stream(self, limit=None, page_size=None): + @property + def _proxy(self) -> "EngagementContext": """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.studio.v1.flow.engagement.EngagementInstance] + :returns: EngagementContext for this EngagementInstance """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) + if self._context is None: + self._context = EngagementContext( + self._version, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return self._context - def list(self, limit=None, page_size=None): + def delete(self) -> bool: """ - Lists EngagementInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the EngagementInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.studio.v1.flow.engagement.EngagementInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.delete() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def delete_async(self) -> bool: """ - Retrieve a single page of EngagementInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the EngagementInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of EngagementInstance - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementPage + :returns: True if delete succeeds, False otherwise """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.delete_async() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return EngagementPage(self._version, response, self._solution) - - def get_page(self, target_url): + def fetch(self) -> "EngagementInstance": """ - Retrieve a specific page of EngagementInstance records from the API. - Request is executed immediately + Fetch the EngagementInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of EngagementInstance - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementPage + :returns: The fetched EngagementInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return EngagementPage(self._version, response, self._solution) + return self._proxy.fetch() - def create(self, to, from_, parameters=values.unset): + async def fetch_async(self) -> "EngagementInstance": """ - Create a new EngagementInstance + Asynchronous coroutine to fetch the EngagementInstance - :param unicode to: The to - :param unicode from_: The from - :param dict parameters: The parameters - :returns: Newly created EngagementInstance - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementInstance + :returns: The fetched EngagementInstance """ - data = values.of({'To': to, 'From': from_, 'Parameters': serialize.object(parameters), }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return EngagementInstance(self._version, payload, flow_sid=self._solution['flow_sid'], ) + return await self._proxy.fetch_async() - def get(self, sid): + @property + def engagement_context(self) -> EngagementContextList: """ - Constructs a EngagementContext - - :param sid: The sid - - :returns: twilio.rest.studio.v1.flow.engagement.EngagementContext - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementContext + Access the engagement_context """ - return EngagementContext(self._version, flow_sid=self._solution['flow_sid'], sid=sid, ) + return self._proxy.engagement_context - def __call__(self, sid): + @property + def steps(self) -> StepList: """ - Constructs a EngagementContext - - :param sid: The sid - - :returns: twilio.rest.studio.v1.flow.engagement.EngagementContext - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementContext + Access the steps """ - return EngagementContext(self._version, flow_sid=self._solution['flow_sid'], sid=sid, ) + return self._proxy.steps - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class EngagementPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class EngagementContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, flow_sid: str, sid: str): """ - Initialize the EngagementPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param flow_sid: The flow_sid + Initialize the EngagementContext - :returns: twilio.rest.studio.v1.flow.engagement.EngagementPage - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementPage + :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(EngagementPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "flow_sid": flow_sid, + "sid": sid, + } + self._uri = "/Flows/{flow_sid}/Engagements/{sid}".format(**self._solution) - def get_instance(self, payload): + self._engagement_context: Optional[EngagementContextList] = None + self._steps: Optional[StepList] = None + + def delete(self) -> bool: """ - Build an instance of EngagementInstance + Deletes the EngagementInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.studio.v1.flow.engagement.EngagementInstance - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementInstance + :returns: True if delete succeeds, False otherwise """ - return EngagementInstance(self._version, payload, flow_sid=self._solution['flow_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the EngagementInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class EngagementContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, flow_sid, sid): + def fetch(self) -> EngagementInstance: """ - Initialize the EngagementContext + Fetch the EngagementInstance - :param Version version: Version that contains the resource - :param flow_sid: The flow_sid - :param sid: The sid - :returns: twilio.rest.studio.v1.flow.engagement.EngagementContext - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementContext + :returns: The fetched EngagementInstance """ - super(EngagementContext, self).__init__(version) - # Path Solution - self._solution = {'flow_sid': flow_sid, 'sid': sid, } - self._uri = '/Flows/{flow_sid}/Engagements/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - # Dependents - self._steps = None - self._engagement_context = None + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return EngagementInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> EngagementInstance: """ - Fetch a EngagementInstance + Asynchronous coroutine to fetch the EngagementInstance + - :returns: Fetched EngagementInstance - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementInstance + :returns: The fetched EngagementInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], ) @property - def steps(self): + def engagement_context(self) -> EngagementContextList: """ - Access the steps - - :returns: twilio.rest.studio.v1.flow.engagement.step.StepList - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepList + Access the engagement_context """ - if self._steps is None: - self._steps = StepList( + if self._engagement_context is None: + self._engagement_context = EngagementContextList( self._version, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['sid'], + self._solution["flow_sid"], + self._solution["sid"], ) - return self._steps + return self._engagement_context @property - def engagement_context(self): + def steps(self) -> StepList: """ - Access the engagement_context - - :returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList - :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList + Access the steps """ - if self._engagement_context is None: - self._engagement_context = EngagementContextList( + if self._steps is None: + self._steps = StepList( self._version, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['sid'], + self._solution["flow_sid"], + self._solution["sid"], ) - return self._engagement_context + return self._steps - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class EngagementInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class EngagementPage(Page): - class Status(object): - ACTIVE = "active" - ENDED = "ended" + def get_instance(self, payload: Dict[str, Any]) -> EngagementInstance: + """ + Build an instance of EngagementInstance - def __init__(self, version, payload, flow_sid, sid=None): + :param payload: Payload response from the API """ - Initialize the EngagementInstance + return EngagementInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) - :returns: twilio.rest.studio.v1.flow.engagement.EngagementInstance - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementInstance + def __repr__(self) -> str: """ - super(EngagementInstance, self).__init__(version) + Provide a friendly representation - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'flow_sid': payload['flow_sid'], - 'contact_sid': payload['contact_sid'], - 'contact_channel_address': payload['contact_channel_address'], - 'context': payload['context'], - 'status': payload['status'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - 'links': payload['links'], - } + :returns: Machine friendly representation + """ + return "" - # Context - self._context = None - self._solution = {'flow_sid': flow_sid, 'sid': sid or self._properties['sid'], } - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context +class EngagementList(ListResource): - :returns: EngagementContext for this EngagementInstance - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementContext + def __init__(self, version: Version, flow_sid: str): """ - if self._context is None: - self._context = EngagementContext( - self._version, - flow_sid=self._solution['flow_sid'], - sid=self._solution['sid'], - ) - return self._context + Initialize the EngagementList - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow to read Engagements from. - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode """ - return self._properties['account_sid'] + super().__init__(version) - @property - def flow_sid(self): + # 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: """ - :returns: The flow_sid - :rtype: unicode + 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 """ - return self._properties['flow_sid'] - @property - def contact_sid(self): + 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: """ - :returns: The contact_sid - :rtype: unicode + 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 """ - return self._properties['contact_sid'] - @property - def contact_channel_address(self): + 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]: """ - :returns: The contact_channel_address - :rtype: unicode + 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 """ - return self._properties['contact_channel_address'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def context(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EngagementInstance]: """ - :returns: The context - :rtype: dict + 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 """ - return self._properties['context'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def status(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EngagementInstance]: """ - :returns: The status - :rtype: EngagementInstance.Status + 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 self._properties['status'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def date_created(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EngagementInstance]: """ - :returns: The date_created - :rtype: datetime + 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 self._properties['date_created'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def date_updated(self): + 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: """ - :returns: The date_updated - :rtype: datetime + 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 """ - return self._properties['date_updated'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def url(self): + headers = values.of({"Content-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: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def links(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The links - :rtype: unicode + 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 """ - return self._properties['links'] + response = self._version.domain.twilio.request("GET", target_url) + return EngagementPage(self._version, response, self._solution) - def fetch(self): + async def get_page_async(self, target_url: str) -> EngagementPage: """ - Fetch a EngagementInstance + 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: Fetched EngagementInstance - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementInstance + :returns: Page of EngagementInstance """ - return self._proxy.fetch() + response = await self._version.domain.twilio.request_async("GET", target_url) + return EngagementPage(self._version, response, self._solution) - @property - def steps(self): + def get(self, sid: str) -> EngagementContext: """ - Access the steps + Constructs a EngagementContext - :returns: twilio.rest.studio.v1.flow.engagement.step.StepList - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepList + :param sid: The SID of the Engagement resource to fetch. """ - return self._proxy.steps + return EngagementContext( + self._version, flow_sid=self._solution["flow_sid"], sid=sid + ) - @property - def engagement_context(self): + def __call__(self, sid: str) -> EngagementContext: """ - Access the engagement_context + Constructs a EngagementContext - :returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList - :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList + :param sid: The SID of the Engagement resource to fetch. """ - return self._proxy.engagement_context + return EngagementContext( + self._version, flow_sid=self._solution["flow_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/studio/v1/flow/engagement/engagement_context.py b/twilio/rest/studio/v1/flow/engagement/engagement_context.py index 3e7df10ccc..73161011eb 100644 --- a/twilio/rest/studio/v1/flow/engagement/engagement_context.py +++ b/twilio/rest/studio/v1/flow/engagement/engagement_context.py @@ -1,273 +1,219 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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.page import Page +from twilio.base.version import Version -class EngagementContextList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +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 - def __init__(self, version, flow_sid, engagement_sid): + @property + def _proxy(self) -> "EngagementContextContext": """ - Initialize the EngagementContextList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param flow_sid: The flow_sid - :param engagement_sid: The engagement_sid + :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 - :returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList - :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList + def fetch(self) -> "EngagementContextInstance": """ - super(EngagementContextList, self).__init__(version) + Fetch the EngagementContextInstance - # Path Solution - self._solution = {'flow_sid': flow_sid, 'engagement_sid': engagement_sid, } - def get(self): + :returns: The fetched EngagementContextInstance """ - Constructs a EngagementContextContext + return self._proxy.fetch() - :returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextContext - :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextContext + async def fetch_async(self) -> "EngagementContextInstance": """ - return EngagementContextContext( - self._version, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['engagement_sid'], - ) + Asynchronous coroutine to fetch the EngagementContextInstance - def __call__(self): - """ - Constructs a EngagementContextContext - :returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextContext - :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextContext + :returns: The fetched EngagementContextInstance """ - return EngagementContextContext( - self._version, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['engagement_sid'], - ) + return await self._proxy.fetch_async() - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class EngagementContextPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class EngagementContextContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, flow_sid: str, engagement_sid: str): """ - Initialize the EngagementContextPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param flow_sid: The flow_sid - :param engagement_sid: The engagement_sid + Initialize the EngagementContextContext - :returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextPage - :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextPage + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow. + :param engagement_sid: The SID of the Engagement. """ - super(EngagementContextPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + } + self._uri = "/Flows/{flow_sid}/Engagements/{engagement_sid}/Context".format( + **self._solution + ) - def get_instance(self, payload): + def fetch(self) -> EngagementContextInstance: """ - Build an instance of EngagementContextInstance + Fetch the EngagementContextInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextInstance - :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextInstance + :returns: The fetched EngagementContextInstance """ - return EngagementContextInstance( - self._version, - payload, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['engagement_sid'], - ) - def __repr__(self): - """ - Provide a friendly representation + headers = values.of({}) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Accept"] = "application/json" + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) -class EngagementContextContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return EngagementContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + ) - def __init__(self, version, flow_sid, engagement_sid): + async def fetch_async(self) -> EngagementContextInstance: """ - Initialize the EngagementContextContext + Asynchronous coroutine to fetch the EngagementContextInstance - :param Version version: Version that contains the resource - :param flow_sid: The flow_sid - :param engagement_sid: The engagement_sid - :returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextContext - :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextContext + :returns: The fetched EngagementContextInstance """ - super(EngagementContextContext, self).__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): - """ - Fetch a EngagementContextInstance + headers = values.of({}) - :returns: Fetched EngagementContextInstance - :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextInstance - """ - params = values.of({}) + headers["Accept"] = "application/json" - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class EngagementContextInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, payload, flow_sid, engagement_sid): """ - Initialize the EngagementContextInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextInstance - :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextInstance - """ - super(EngagementContextInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'context': payload['context'], - 'engagement_sid': payload['engagement_sid'], - 'flow_sid': payload['flow_sid'], - 'url': payload['url'], - } - # Context - self._context = None - self._solution = {'flow_sid': flow_sid, 'engagement_sid': engagement_sid, } +class EngagementContextList(ListResource): - @property - def _proxy(self): + def __init__(self, version: Version, flow_sid: str, engagement_sid: str): """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Initialize the EngagementContextList - :returns: EngagementContextContext for this EngagementContextInstance - :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextContext - """ - 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 + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow. + :param engagement_sid: The SID of the Engagement. - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode """ - return self._properties['account_sid'] + super().__init__(version) - @property - def context(self): - """ - :returns: The context - :rtype: dict - """ - return self._properties['context'] - - @property - def engagement_sid(self): - """ - :returns: The engagement_sid - :rtype: unicode - """ - return self._properties['engagement_sid'] + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + } - @property - def flow_sid(self): - """ - :returns: The flow_sid - :rtype: unicode + def get(self) -> EngagementContextContext: """ - return self._properties['flow_sid'] + Constructs a EngagementContextContext - @property - def url(self): - """ - :returns: The url - :rtype: unicode """ - return self._properties['url'] + return EngagementContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + ) - def fetch(self): + def __call__(self) -> EngagementContextContext: """ - Fetch a EngagementContextInstance + Constructs a EngagementContextContext - :returns: Fetched EngagementContextInstance - :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextInstance """ - return self._proxy.fetch() + return EngagementContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/studio/v1/flow/engagement/step/__init__.py b/twilio/rest/studio/v1/flow/engagement/step/__init__.py index 63db5c9188..a5017c3313 100644 --- a/twilio/rest/studio/v1/flow/engagement/step/__init__.py +++ b/twilio/rest/studio/v1/flow/engagement/step/__init__.py @@ -1,463 +1,496 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 StepList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, flow_sid, engagement_sid): - """ - Initialize the StepList +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") - :param Version version: Version that contains the resource - :param flow_sid: The flow_sid - :param engagement_sid: The engagement_sid + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + "sid": sid or self.sid, + } + self._context: Optional[StepContext] = None - :returns: twilio.rest.studio.v1.flow.engagement.step.StepList - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepList + @property + def _proxy(self) -> "StepContext": """ - super(StepList, self).__init__(version) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - # Path Solution - self._solution = {'flow_sid': flow_sid, 'engagement_sid': engagement_sid, } - self._uri = '/Flows/{flow_sid}/Engagements/{engagement_sid}/Steps'.format(**self._solution) + :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 stream(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the StepInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.studio.v1.flow.engagement.step.StepInstance] + :returns: The fetched StepInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(page_size=limits['page_size'], ) + async def fetch_async(self) -> "StepInstance": + """ + Asynchronous coroutine to fetch the StepInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + return await self._proxy.fetch_async() - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + @property + def step_context(self) -> StepContextList: + """ + Access the step_context + """ + return self._proxy.step_context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.studio.v1.flow.engagement.step.StepInstance] + def __repr__(self) -> str: """ - return list(self.stream(limit=limit, page_size=page_size, )) + Provide a friendly representation - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + :returns: Machine friendly representation """ - Retrieve a single page of StepInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of StepInstance - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepPage +class StepContext(InstanceContext): + + def __init__(self, version: Version, flow_sid: str, engagement_sid: str, sid: str): """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the StepContext - response = self._version.page( - 'GET', - self._uri, - params=params, + :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 ) - return StepPage(self._version, response, self._solution) + self._step_context: Optional[StepContextList] = None - def get_page(self, target_url): + def fetch(self) -> StepInstance: """ - Retrieve a specific page of StepInstance records from the API. - Request is executed immediately + Fetch the StepInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of StepInstance - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepPage + :returns: The fetched StepInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return StepPage(self._version, response, self._solution) + headers = values.of({}) - def get(self, sid): - """ - Constructs a StepContext + headers["Accept"] = "application/json" - :param sid: The sid + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.studio.v1.flow.engagement.step.StepContext - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepContext - """ - return StepContext( + return StepInstance( self._version, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['engagement_sid'], - sid=sid, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + sid=self._solution["sid"], ) - def __call__(self, sid): + async def fetch_async(self) -> StepInstance: """ - Constructs a StepContext + Asynchronous coroutine to fetch the StepInstance - :param sid: The sid - :returns: twilio.rest.studio.v1.flow.engagement.step.StepContext - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepContext + :returns: The fetched StepInstance """ - return StepContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return StepInstance( self._version, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['engagement_sid'], - sid=sid, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + @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 - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) class StepPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, response, solution): - """ - Initialize the StepPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param flow_sid: The flow_sid - :param engagement_sid: The engagement_sid - - :returns: twilio.rest.studio.v1.flow.engagement.step.StepPage - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepPage - """ - super(StepPage, self).__init__(version, response) - # Path Solution - self._solution = solution - - def get_instance(self, payload): + def get_instance(self, payload: Dict[str, Any]) -> StepInstance: """ Build an instance of StepInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.studio.v1.flow.engagement.step.StepInstance - :rtype: twilio.rest.studio.v1.flow.engagement.step.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'], + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class StepContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class StepList(ListResource): - def __init__(self, version, flow_sid, engagement_sid, sid): + def __init__(self, version: Version, flow_sid: str, engagement_sid: str): """ - Initialize the StepContext + Initialize the StepList - :param Version version: Version that contains the resource - :param flow_sid: The flow_sid - :param engagement_sid: The engagement_sid - :param sid: The sid + :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. - :returns: twilio.rest.studio.v1.flow.engagement.step.StepContext - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepContext """ - super(StepContext, self).__init__(version) + 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) - - # Dependents - self._step_context = None + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + } + self._uri = "/Flows/{flow_sid}/Engagements/{engagement_sid}/Steps".format( + **self._solution + ) - def fetch(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[StepInstance]: """ - Fetch a 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: Fetched StepInstance - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepInstance + :returns: Generator that will yield up to limit results """ - params = values.of({}) + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) + return self._version.stream(page, limits["limit"]) - 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): + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[StepInstance]: """ - Access the step_context + 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. - :returns: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextList - :rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextList - """ - if self._step_context is None: - self._step_context = StepContextList( - self._version, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['engagement_sid'], - step_sid=self._solution['sid'], - ) - return self._step_context + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - def __repr__(self): + :returns: Generator that will yield up to limit results """ - Provide a friendly representation + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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. -class StepInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, payload, flow_sid, engagement_sid, sid=None): - """ - Initialize the StepInstance - - :returns: twilio.rest.studio.v1.flow.engagement.step.StepInstance - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepInstance - """ - super(StepInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'flow_sid': payload['flow_sid'], - 'engagement_sid': payload['engagement_sid'], - 'name': payload['name'], - 'context': payload['context'], - 'transitioned_from': payload['transitioned_from'], - 'transitioned_to': payload['transitioned_to'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - 'links': payload['links'], - } + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - # Context - self._context = None - self._solution = { - 'flow_sid': flow_sid, - 'engagement_sid': engagement_sid, - 'sid': sid or self._properties['sid'], - } + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def _proxy(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[StepInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: StepContext for this StepInstance - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepContext + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - 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 [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, ) - return self._context + ] - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + 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: """ - return self._properties['sid'] + Retrieve a single page of StepInstance records from the API. + Request is executed immediately - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_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 - @property - def flow_sid(self): - """ - :returns: The flow_sid - :rtype: unicode + :returns: Page of StepInstance """ - return self._properties['flow_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def engagement_sid(self): - """ - :returns: The engagement_sid - :rtype: unicode - """ - return self._properties['engagement_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def name(self): - """ - :returns: The name - :rtype: unicode - """ - return self._properties['name'] + headers["Accept"] = "application/json" - @property - def context(self): - """ - :returns: The context - :rtype: dict - """ - return self._properties['context'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return StepPage(self._version, response, self._solution) - @property - def transitioned_from(self): + 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: """ - :returns: The transitioned_from - :rtype: unicode - """ - return self._properties['transitioned_from'] + Asynchronously retrieve a single page of StepInstance records from the API. + Request is executed immediately - @property - def transitioned_to(self): - """ - :returns: The transitioned_to - :rtype: unicode - """ - return self._properties['transitioned_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 - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime + :returns: Page of StepInstance """ - return self._properties['date_created'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def url(self): + 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: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + response = self._version.domain.twilio.request("GET", target_url) + return StepPage(self._version, response, self._solution) - @property - def links(self): + async def get_page_async(self, target_url: str) -> StepPage: """ - :returns: The links - :rtype: unicode + 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 """ - return self._properties['links'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return StepPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> StepContext: """ - Fetch a StepInstance + Constructs a StepContext - :returns: Fetched StepInstance - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepInstance + :param sid: The SID of the Step resource to fetch. """ - return self._proxy.fetch() + return StepContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + sid=sid, + ) - @property - def step_context(self): + def __call__(self, sid: str) -> StepContext: """ - Access the step_context + Constructs a StepContext - :returns: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextList - :rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextList + :param sid: The SID of the Step resource to fetch. """ - return self._proxy.step_context + return StepContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/studio/v1/flow/engagement/step/step_context.py b/twilio/rest/studio/v1/flow/engagement/step/step_context.py index 93160c858c..6b299ebe5d 100644 --- a/twilio/rest/studio/v1/flow/engagement/step/step_context.py +++ b/twilio/rest/studio/v1/flow/engagement/step/step_context.py @@ -1,290 +1,236 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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.page import Page +from twilio.base.version import Version -class StepContextList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +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 - def __init__(self, version, flow_sid, engagement_sid, step_sid): + @property + def _proxy(self) -> "StepContextContext": """ - Initialize the StepContextList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param flow_sid: The flow_sid - :param engagement_sid: The engagement_sid - :param step_sid: The step_sid + :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 - :returns: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextList - :rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextList + def fetch(self) -> "StepContextInstance": """ - super(StepContextList, self).__init__(version) + Fetch the StepContextInstance - # Path Solution - self._solution = {'flow_sid': flow_sid, 'engagement_sid': engagement_sid, 'step_sid': step_sid, } - def get(self): + :returns: The fetched StepContextInstance """ - Constructs a StepContextContext + return self._proxy.fetch() - :returns: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextContext - :rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextContext + async def fetch_async(self) -> "StepContextInstance": """ - return StepContextContext( - self._version, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['engagement_sid'], - step_sid=self._solution['step_sid'], - ) + Asynchronous coroutine to fetch the StepContextInstance - def __call__(self): - """ - Constructs a StepContextContext - :returns: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextContext - :rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextContext + :returns: The fetched StepContextInstance """ - return StepContextContext( - self._version, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['engagement_sid'], - step_sid=self._solution['step_sid'], - ) + return await self._proxy.fetch_async() - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class StepContextPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class StepContextContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__( + self, version: Version, flow_sid: str, engagement_sid: str, step_sid: str + ): """ - Initialize the StepContextPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param flow_sid: The flow_sid - :param engagement_sid: The engagement_sid - :param step_sid: The step_sid + Initialize the StepContextContext - :returns: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextPage - :rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextPage + :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(StepContextPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def fetch(self) -> StepContextInstance: """ - Build an instance of StepContextInstance + Fetch the StepContextInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextInstance - :rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextInstance + :returns: The fetched StepContextInstance """ - 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): - """ - Provide a friendly representation + headers = values.of({}) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Accept"] = "application/json" + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) -class StepContextContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return StepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + step_sid=self._solution["step_sid"], + ) - def __init__(self, version, flow_sid, engagement_sid, step_sid): + async def fetch_async(self) -> StepContextInstance: """ - Initialize the StepContextContext + Asynchronous coroutine to fetch the StepContextInstance - :param Version version: Version that contains the resource - :param flow_sid: The flow_sid - :param engagement_sid: The engagement_sid - :param step_sid: The step_sid - :returns: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextContext - :rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextContext + :returns: The fetched StepContextInstance """ - super(StepContextContext, self).__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): - """ - Fetch a StepContextInstance + headers = values.of({}) - :returns: Fetched StepContextInstance - :rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextInstance - """ - params = values.of({}) + headers["Accept"] = "application/json" - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + step_sid=self._solution["step_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class StepContextInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, payload, flow_sid, engagement_sid, step_sid): """ - Initialize the StepContextInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextInstance - :rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextInstance - """ - super(StepContextInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'context': payload['context'], - 'engagement_sid': payload['engagement_sid'], - 'flow_sid': payload['flow_sid'], - 'step_sid': payload['step_sid'], - 'url': payload['url'], - } - # Context - self._context = None - self._solution = {'flow_sid': flow_sid, 'engagement_sid': engagement_sid, 'step_sid': step_sid, } +class StepContextList(ListResource): - @property - def _proxy(self): + def __init__( + self, version: Version, flow_sid: str, engagement_sid: str, step_sid: str + ): """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Initialize the StepContextList - :returns: StepContextContext for this StepContextInstance - :rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextContext - """ - 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 + :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 - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode """ - return self._properties['account_sid'] + super().__init__(version) - @property - def context(self): - """ - :returns: The context - :rtype: dict - """ - return self._properties['context'] - - @property - def engagement_sid(self): - """ - :returns: The engagement_sid - :rtype: unicode - """ - return self._properties['engagement_sid'] - - @property - def flow_sid(self): - """ - :returns: The flow_sid - :rtype: unicode - """ - return self._properties['flow_sid'] + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + "step_sid": step_sid, + } - @property - def step_sid(self): - """ - :returns: The step_sid - :rtype: unicode + def get(self) -> StepContextContext: """ - return self._properties['step_sid'] + Constructs a StepContextContext - @property - def url(self): - """ - :returns: The url - :rtype: unicode """ - return self._properties['url'] + return StepContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + step_sid=self._solution["step_sid"], + ) - def fetch(self): + def __call__(self) -> StepContextContext: """ - Fetch a StepContextInstance + Constructs a StepContextContext - :returns: Fetched StepContextInstance - :rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextInstance """ - return self._proxy.fetch() + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" 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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" 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 "" + + +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 "" 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 "" 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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "" + + +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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "" + + +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 "" 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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "" + + +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 "" + + +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 "" 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 "" diff --git a/twilio/rest/sync/__init__.py b/twilio/rest/sync/__init__.py index 6576b6e383..37b9ce03d6 100644 --- a/twilio/rest/sync/__init__.py +++ b/twilio/rest/sync/__init__.py @@ -1,53 +1,15 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" +from warnings import warn -from twilio.base.domain import Domain -from twilio.rest.sync.v1 import V1 +from twilio.rest.sync.SyncBase import SyncBase +from twilio.rest.sync.v1.service import ServiceList -class Sync(Domain): - - def __init__(self, twilio): - """ - Initialize the Sync Domain - - :returns: Domain for Sync - :rtype: twilio.rest.sync.Sync - """ - super(Sync, self).__init__(twilio) - - self.base_url = 'https://sync.twilio.com' - - # Versions - self._v1 = None - +class Sync(SyncBase): @property - def v1(self): - """ - :returns: Version v1 of sync - :rtype: twilio.rest.sync.v1.V1 - """ - if self._v1 is None: - self._v1 = V1(self) - return self._v1 - - @property - def services(self): - """ - :rtype: twilio.rest.sync.v1.service.ServiceList - """ + def services(self) -> ServiceList: + warn( + "services is deprecated. Use v1.services instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v1.services - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/sync/v1/__init__.py b/twilio/rest/sync/v1/__init__.py index c1aab31243..e98201bd41 100644 --- a/twilio/rest/sync/v1/__init__.py +++ b/twilio/rest/sync/v1/__init__.py @@ -1,42 +1,43 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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): + def __init__(self, domain: Domain): """ Initialize the V1 version of Sync - :returns: V1 version of Sync - :rtype: twilio.rest.sync.v1.V1.V1 + :param domain: The Twilio.sync domain """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._services = None + super().__init__(domain, "v1") + self._services: Optional[ServiceList] = None @property - def services(self): - """ - :rtype: twilio.rest.sync.v1.service.ServiceList - """ + def services(self) -> ServiceList: if self._services is None: self._services = ServiceList(self) return self._services - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/sync/v1/service/__init__.py b/twilio/rest/sync/v1/service/__init__.py index 902dc5795d..d17491d3cb 100644 --- a/twilio/rest/sync/v1/service/__init__.py +++ b/twilio/rest/sync/v1/service/__init__.py @@ -1,16 +1,24 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 @@ -18,565 +26,821 @@ from twilio.rest.sync.v1.service.sync_stream import SyncStreamList -class ServiceList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version): - """ - Initialize the ServiceList +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") - :param Version version: Version that contains the resource + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None - :returns: twilio.rest.sync.v1.service.ServiceList - :rtype: twilio.rest.sync.v1.service.ServiceList + @property + def _proxy(self) -> "ServiceContext": """ - super(ServiceList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Services'.format(**self._solution) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def create(self, friendly_name=values.unset, webhook_url=values.unset, - reachability_webhooks_enabled=values.unset, - acl_enabled=values.unset): + :returns: ServiceContext for this ServiceInstance """ - Create a new ServiceInstance - - :param unicode friendly_name: The friendly_name - :param unicode webhook_url: The webhook_url - :param bool reachability_webhooks_enabled: The reachability_webhooks_enabled - :param bool acl_enabled: The acl_enabled + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: Newly created ServiceInstance - :rtype: twilio.rest.sync.v1.service.ServiceInstance + def delete(self) -> bool: """ - data = values.of({ - 'FriendlyName': friendly_name, - 'WebhookUrl': webhook_url, - 'ReachabilityWebhooksEnabled': reachability_webhooks_enabled, - 'AclEnabled': acl_enabled, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + Deletes the ServiceInstance - return ServiceInstance(self._version, payload, ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.ServiceInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the ServiceInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the ServiceInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.ServiceInstance] + :returns: The fetched ServiceInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_async(self) -> "ServiceInstance": """ - Retrieve a single page of ServiceInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the ServiceInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of ServiceInstance - :rtype: twilio.rest.sync.v1.service.ServicePage + :returns: The fetched ServiceInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + return await self._proxy.fetch_async() - return ServicePage(self._version, response, self._solution) - - def get_page(self, target_url): + 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": """ - Retrieve a specific page of ServiceInstance records from the API. - Request is executed immediately + Update the ServiceInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of ServiceInstance - :rtype: twilio.rest.sync.v1.service.ServicePage + :returns: The updated ServiceInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, ) - return ServicePage(self._version, response, self._solution) + 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, + ) - def get(self, sid): + @property + def documents(self) -> DocumentList: """ - Constructs a ServiceContext - - :param sid: The sid - - :returns: twilio.rest.sync.v1.service.ServiceContext - :rtype: twilio.rest.sync.v1.service.ServiceContext + Access the documents """ - return ServiceContext(self._version, sid=sid, ) + return self._proxy.documents - def __call__(self, sid): + @property + def sync_lists(self) -> SyncListList: """ - Constructs a ServiceContext + Access the sync_lists + """ + return self._proxy.sync_lists - :param sid: The sid + @property + def sync_maps(self) -> SyncMapList: + """ + Access the sync_maps + """ + return self._proxy.sync_maps - :returns: twilio.rest.sync.v1.service.ServiceContext - :rtype: twilio.rest.sync.v1.service.ServiceContext + @property + def sync_streams(self) -> SyncStreamList: + """ + Access the sync_streams """ - return ServiceContext(self._version, sid=sid, ) + return self._proxy.sync_streams - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ServicePage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class ServiceContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the ServicePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the ServiceContext - :returns: twilio.rest.sync.v1.service.ServicePage - :rtype: twilio.rest.sync.v1.service.ServicePage + :param version: Version that contains the resource + :param sid: The SID of the Service resource to update. """ - super(ServicePage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of ServiceInstance + Deletes the ServiceInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.sync.v1.service.ServiceInstance - :rtype: twilio.rest.sync.v1.service.ServiceInstance + :returns: True if delete succeeds, False otherwise """ - return ServiceInstance(self._version, payload, ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the ServiceInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class ServiceContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, sid): + def fetch(self) -> ServiceInstance: """ - Initialize the ServiceContext + Fetch the ServiceInstance - :param Version version: Version that contains the resource - :param sid: The sid - :returns: twilio.rest.sync.v1.service.ServiceContext - :rtype: twilio.rest.sync.v1.service.ServiceContext + :returns: The fetched ServiceInstance """ - super(ServiceContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Services/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._documents = None - self._sync_lists = None - self._sync_maps = None - self._sync_streams = None + headers["Accept"] = "application/json" - def fetch(self): + 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: """ - Fetch a ServiceInstance + Asynchronous coroutine to fetch the ServiceInstance + - :returns: Fetched ServiceInstance - :rtype: twilio.rest.sync.v1.service.ServiceInstance + :returns: The fetched ServiceInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) + headers = values.of({}) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" - def delete(self): - """ - Deletes the ServiceInstance + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def update(self, webhook_url=values.unset, friendly_name=values.unset, - reachability_webhooks_enabled=values.unset, - acl_enabled=values.unset): + 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 unicode webhook_url: The webhook_url - :param unicode friendly_name: The friendly_name - :param bool reachability_webhooks_enabled: The reachability_webhooks_enabled - :param bool acl_enabled: The acl_enabled + :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({}) - :returns: Updated ServiceInstance - :rtype: twilio.rest.sync.v1.service.ServiceInstance - """ - data = values.of({ - 'WebhookUrl': webhook_url, - 'FriendlyName': friendly_name, - 'ReachabilityWebhooksEnabled': reachability_webhooks_enabled, - 'AclEnabled': acl_enabled, - }) + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" payload = self._version.update( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + 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): + def documents(self) -> DocumentList: """ Access the documents - - :returns: twilio.rest.sync.v1.service.document.DocumentList - :rtype: twilio.rest.sync.v1.service.document.DocumentList """ if self._documents is None: - self._documents = DocumentList(self._version, service_sid=self._solution['sid'], ) + self._documents = DocumentList( + self._version, + self._solution["sid"], + ) return self._documents @property - def sync_lists(self): + def sync_lists(self) -> SyncListList: """ Access the sync_lists - - :returns: twilio.rest.sync.v1.service.sync_list.SyncListList - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListList """ if self._sync_lists is None: - self._sync_lists = SyncListList(self._version, service_sid=self._solution['sid'], ) + self._sync_lists = SyncListList( + self._version, + self._solution["sid"], + ) return self._sync_lists @property - def sync_maps(self): + def sync_maps(self) -> SyncMapList: """ Access the sync_maps - - :returns: twilio.rest.sync.v1.service.sync_map.SyncMapList - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapList """ if self._sync_maps is None: - self._sync_maps = SyncMapList(self._version, service_sid=self._solution['sid'], ) + self._sync_maps = SyncMapList( + self._version, + self._solution["sid"], + ) return self._sync_maps @property - def sync_streams(self): + def sync_streams(self) -> SyncStreamList: """ Access the sync_streams - - :returns: twilio.rest.sync.v1.service.sync_stream.SyncStreamList - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamList """ if self._sync_streams is None: - self._sync_streams = SyncStreamList(self._version, service_sid=self._solution['sid'], ) + self._sync_streams = SyncStreamList( + self._version, + self._solution["sid"], + ) return self._sync_streams - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ServiceInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, payload, sid=None): - """ - Initialize the ServiceInstance - - :returns: twilio.rest.sync.v1.service.ServiceInstance - :rtype: twilio.rest.sync.v1.service.ServiceInstance - """ - super(ServiceInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'unique_name': payload['unique_name'], - 'account_sid': payload['account_sid'], - 'friendly_name': payload['friendly_name'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - 'webhook_url': payload['webhook_url'], - 'reachability_webhooks_enabled': payload['reachability_webhooks_enabled'], - 'acl_enabled': payload['acl_enabled'], - 'links': payload['links'], - } - - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } +class ServicePage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of ServiceInstance - :returns: ServiceContext for this ServiceInstance - :rtype: twilio.rest.sync.v1.service.ServiceContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = ServiceContext(self._version, sid=self._solution['sid'], ) - return self._context + return ServiceInstance(self._version, payload) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['sid'] + Provide a friendly representation - @property - def unique_name(self): - """ - :returns: The unique_name - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['unique_name'] + return "" - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] +class ServiceList(ListResource): - @property - def date_created(self): + def __init__(self, version: Version): """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + Initialize the ServiceList - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + :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"}) - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def webhook_url(self): - """ - :returns: The webhook_url - :rtype: unicode - """ - return self._properties['webhook_url'] + headers["Accept"] = "application/json" - @property - def reachability_webhooks_enabled(self): - """ - :returns: The reachability_webhooks_enabled - :rtype: bool + 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]: """ - return self._properties['reachability_webhooks_enabled'] + 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. - @property - def acl_enabled(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The acl_enabled - :rtype: bool + 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]: """ - return self._properties['acl_enabled'] + 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. - @property - def links(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The links - :rtype: unicode + 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]: """ - return self._properties['links'] + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - def fetch(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - Fetch a ServiceInstance + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - :returns: Fetched ServiceInstance - :rtype: twilio.rest.sync.v1.service.ServiceInstance + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: """ - return self._proxy.fetch() + 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. - def delete(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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: """ - Deletes the ServiceInstance + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param page_token: PageToken provided by the API + :param page_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 """ - return self._proxy.delete() + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def update(self, webhook_url=values.unset, friendly_name=values.unset, - reachability_webhooks_enabled=values.unset, - acl_enabled=values.unset): + 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: """ - Update the ServiceInstance + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - :param unicode webhook_url: The webhook_url - :param unicode friendly_name: The friendly_name - :param bool reachability_webhooks_enabled: The reachability_webhooks_enabled - :param bool acl_enabled: The acl_enabled + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - :returns: Updated ServiceInstance - :rtype: twilio.rest.sync.v1.service.ServiceInstance + :returns: Page of ServiceInstance """ - return self._proxy.update( - webhook_url=webhook_url, - friendly_name=friendly_name, - reachability_webhooks_enabled=reachability_webhooks_enabled, - acl_enabled=acl_enabled, + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } ) - @property - def documents(self): + headers = values.of({"Content-Type": "application/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: """ - Access the documents + 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: twilio.rest.sync.v1.service.document.DocumentList - :rtype: twilio.rest.sync.v1.service.document.DocumentList + :returns: Page of ServiceInstance """ - return self._proxy.documents + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) - @property - def sync_lists(self): + async def get_page_async(self, target_url: str) -> ServicePage: """ - Access the sync_lists + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately - :returns: twilio.rest.sync.v1.service.sync_list.SyncListList - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListList + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance """ - return self._proxy.sync_lists + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) - @property - def sync_maps(self): + def get(self, sid: str) -> ServiceContext: """ - Access the sync_maps + Constructs a ServiceContext - :returns: twilio.rest.sync.v1.service.sync_map.SyncMapList - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapList + :param sid: The SID of the Service resource to update. """ - return self._proxy.sync_maps + return ServiceContext(self._version, sid=sid) - @property - def sync_streams(self): + def __call__(self, sid: str) -> ServiceContext: """ - Access the sync_streams + Constructs a ServiceContext - :returns: twilio.rest.sync.v1.service.sync_stream.SyncStreamList - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamList + :param sid: The SID of the Service resource to update. """ - return self._proxy.sync_streams + return ServiceContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/sync/v1/service/document/__init__.py b/twilio/rest/sync/v1/service/document/__init__.py index 3e1e4e50ee..fe64f629a8 100644 --- a/twilio/rest/sync/v1/service/document/__init__.py +++ b/twilio/rest/sync/v1/service/document/__init__.py @@ -1,515 +1,723 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 - +from twilio.rest.sync.v1.service.document.document_permission import ( + DocumentPermissionList, +) -class DocumentList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - def __init__(self, version, service_sid): - """ - Initialize the DocumentList +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") - :param Version version: Version that contains the resource - :param service_sid: The service_sid + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[DocumentContext] = None - :returns: twilio.rest.sync.v1.service.document.DocumentList - :rtype: twilio.rest.sync.v1.service.document.DocumentList + @property + def _proxy(self) -> "DocumentContext": """ - super(DocumentList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Documents'.format(**self._solution) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def create(self, unique_name=values.unset, data=values.unset, ttl=values.unset): + :returns: DocumentContext for this DocumentInstance """ - Create a new DocumentInstance - - :param unicode unique_name: The unique_name - :param dict data: The data - :param unicode ttl: The ttl + if self._context is None: + self._context = DocumentContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: Newly created DocumentInstance - :rtype: twilio.rest.sync.v1.service.document.DocumentInstance + def delete(self) -> bool: """ - data = values.of({'UniqueName': unique_name, 'Data': serialize.object(data), 'Ttl': ttl, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + Deletes the DocumentInstance - return DocumentInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.document.DocumentInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the DocumentInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the DocumentInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.document.DocumentInstance] + :returns: The fetched DocumentInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_async(self) -> "DocumentInstance": """ - Retrieve a single page of DocumentInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the DocumentInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of DocumentInstance - :rtype: twilio.rest.sync.v1.service.document.DocumentPage + :returns: The fetched DocumentInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return DocumentPage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def get_page(self, target_url): + def update( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> "DocumentInstance": """ - Retrieve a specific page of DocumentInstance records from the API. - Request is executed immediately + Update the DocumentInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of DocumentInstance - :rtype: twilio.rest.sync.v1.service.document.DocumentPage + :returns: The updated DocumentInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + if_match=if_match, + data=data, + ttl=ttl, ) - return DocumentPage(self._version, response, self._solution) - - def get(self, 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": """ - Constructs a DocumentContext + Asynchronous coroutine to update the DocumentInstance - :param sid: The sid + :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: twilio.rest.sync.v1.service.document.DocumentContext - :rtype: twilio.rest.sync.v1.service.document.DocumentContext + :returns: The updated DocumentInstance """ - return DocumentContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_async( + if_match=if_match, + data=data, + ttl=ttl, + ) - def __call__(self, sid): + @property + def document_permissions(self) -> DocumentPermissionList: """ - Constructs a DocumentContext - - :param sid: The sid - - :returns: twilio.rest.sync.v1.service.document.DocumentContext - :rtype: twilio.rest.sync.v1.service.document.DocumentContext + Access the document_permissions """ - return DocumentContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.document_permissions - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class DocumentPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class DocumentContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the DocumentPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid + Initialize the DocumentContext - :returns: twilio.rest.sync.v1.service.document.DocumentPage - :rtype: twilio.rest.sync.v1.service.document.DocumentPage + :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(DocumentPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Documents/{sid}".format(**self._solution) - def get_instance(self, payload): + self._document_permissions: Optional[DocumentPermissionList] = None + + def delete(self) -> bool: """ - Build an instance of DocumentInstance + Deletes the DocumentInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.sync.v1.service.document.DocumentInstance - :rtype: twilio.rest.sync.v1.service.document.DocumentInstance + :returns: True if delete succeeds, False otherwise """ - return DocumentInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the DocumentInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class DocumentContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, service_sid, sid): + def fetch(self) -> DocumentInstance: """ - Initialize the DocumentContext + Fetch the DocumentInstance - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: The sid - :returns: twilio.rest.sync.v1.service.document.DocumentContext - :rtype: twilio.rest.sync.v1.service.document.DocumentContext + :returns: The fetched DocumentInstance """ - super(DocumentContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Documents/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._document_permissions = None + 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"], + ) - def fetch(self): + async def fetch_async(self) -> DocumentInstance: """ - Fetch a DocumentInstance + Asynchronous coroutine to fetch the DocumentInstance - :returns: Fetched DocumentInstance - :rtype: twilio.rest.sync.v1.service.document.DocumentInstance + + :returns: The fetched DocumentInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + def update( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> DocumentInstance: """ - Deletes the DocumentInstance + Update the DocumentInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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._version.delete('delete', self._uri) - def update(self, data=values.unset, ttl=values.unset): + 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: """ - Update the DocumentInstance + Asynchronous coroutine to update the DocumentInstance - :param dict data: The data - :param unicode ttl: The ttl + :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: Updated DocumentInstance - :rtype: twilio.rest.sync.v1.service.document.DocumentInstance + :returns: The updated DocumentInstance """ - data = values.of({'Data': serialize.object(data), 'Ttl': ttl, }) - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) @property - def document_permissions(self): + def document_permissions(self) -> DocumentPermissionList: """ Access the document_permissions - - :returns: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionList - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionList """ if self._document_permissions is None: self._document_permissions = DocumentPermissionList( self._version, - service_sid=self._solution['service_sid'], - document_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) return self._document_permissions - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class DocumentInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the DocumentInstance - - :returns: twilio.rest.sync.v1.service.document.DocumentInstance - :rtype: twilio.rest.sync.v1.service.document.DocumentInstance - """ - super(DocumentInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'unique_name': payload['unique_name'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'url': payload['url'], - 'links': payload['links'], - 'revision': payload['revision'], - 'data': payload['data'], - 'date_expires': deserialize.iso8601_datetime(payload['date_expires']), - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'created_by': payload['created_by'], - } - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } +class DocumentPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> DocumentInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of DocumentInstance - :returns: DocumentContext for this DocumentInstance - :rtype: twilio.rest.sync.v1.service.document.DocumentContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = DocumentContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + return DocumentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['sid'] + Provide a friendly representation - @property - def unique_name(self): - """ - :returns: The unique_name - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['unique_name'] + return "" - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode +class DocumentList(ListResource): + + def __init__(self, version: Version, service_sid: str): """ - return self._properties['service_sid'] + 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. - @property - def url(self): """ - :returns: The url - :rtype: unicode + 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: """ - return self._properties['url'] + Create the DocumentInstance - @property - def links(self): + :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 """ - :returns: The links - :rtype: unicode + + 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: """ - return self._properties['links'] + Asynchronously create the DocumentInstance - @property - def revision(self): + :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 """ - :returns: The revision - :rtype: unicode + + 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]: """ - return self._properties['revision'] + 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. - @property - def data(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The data - :rtype: dict + 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]: """ - return self._properties['data'] + 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. - @property - def date_expires(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The date_expires - :rtype: datetime + 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]: """ - return self._properties['date_expires'] + Lists DocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def date_created(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The date_created - :rtype: datetime + 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]: """ - return self._properties['date_created'] + 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. - @property - def date_updated(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The date_updated - :rtype: datetime + 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: """ - return self._properties['date_updated'] + Retrieve a single page of DocumentInstance records from the API. + Request is executed immediately - @property - def created_by(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The created_by - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['created_by'] + Asynchronously retrieve a single page of DocumentInstance records from the API. + Request is executed immediately - def fetch(self): + :param page_token: PageToken provided by the API + :param page_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 """ - Fetch a 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) - :returns: Fetched DocumentInstance - :rtype: twilio.rest.sync.v1.service.document.DocumentInstance + def get_page(self, target_url: str) -> DocumentPage: """ - return self._proxy.fetch() + 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 - def delete(self): + :returns: Page of DocumentInstance """ - Deletes the DocumentInstance + response = self._version.domain.twilio.request("GET", target_url) + return DocumentPage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def get_page_async(self, target_url: str) -> DocumentPage: """ - return self._proxy.delete() + Asynchronously retrieve a specific page of DocumentInstance records from the API. + Request is executed immediately - def update(self, data=values.unset, ttl=values.unset): + :param target_url: API-generated URL for the requested results page + + :returns: Page of DocumentInstance """ - Update the DocumentInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return DocumentPage(self._version, response, self._solution) - :param dict data: The data - :param unicode ttl: The ttl + def get(self, sid: str) -> DocumentContext: + """ + Constructs a DocumentContext - :returns: Updated DocumentInstance - :rtype: twilio.rest.sync.v1.service.document.DocumentInstance + :param sid: The SID of the Document resource to update. Can be the Document resource's `sid` or its `unique_name`. """ - return self._proxy.update(data=data, ttl=ttl, ) + return DocumentContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - @property - def document_permissions(self): + def __call__(self, sid: str) -> DocumentContext: """ - Access the document_permissions + Constructs a DocumentContext - :returns: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionList - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionList + :param sid: The SID of the Document resource to update. Can be the Document resource's `sid` or its `unique_name`. """ - return self._proxy.document_permissions + return DocumentContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/sync/v1/service/document/document_permission.py b/twilio/rest/sync/v1/service/document/document_permission.py index 196d0e8968..75a27c969a 100644 --- a/twilio/rest/sync/v1/service/document/document_permission.py +++ b/twilio/rest/sync/v1/service/document/document_permission.py @@ -1,453 +1,617 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import values +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 DocumentPermissionList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +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 - def __init__(self, version, service_sid, document_sid): + @property + def _proxy(self) -> "DocumentPermissionContext": """ - Initialize the DocumentPermissionList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: Sync Service Instance SID. - :param document_sid: Sync Document SID. + :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 - :returns: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionList - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionList + def delete(self) -> bool: """ - super(DocumentPermissionList, self).__init__(version) + Deletes the DocumentPermissionInstance - # 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=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the DocumentPermissionInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the DocumentPermissionInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionInstance] + :returns: The fetched DocumentPermissionInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_async(self) -> "DocumentPermissionInstance": """ - Retrieve a single page of DocumentPermissionInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the DocumentPermissionInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of DocumentPermissionInstance - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionPage + :returns: The fetched DocumentPermissionInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + return await self._proxy.fetch_async() - return DocumentPermissionPage(self._version, response, self._solution) - - def get_page(self, target_url): + def update( + self, read: bool, write: bool, manage: bool + ) -> "DocumentPermissionInstance": """ - Retrieve a specific page of DocumentPermissionInstance records from the API. - Request is executed immediately + Update the DocumentPermissionInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of DocumentPermissionInstance - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionPage + :returns: The updated DocumentPermissionInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + read=read, + write=write, + manage=manage, ) - return DocumentPermissionPage(self._version, response, self._solution) - - def get(self, identity): + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> "DocumentPermissionInstance": """ - Constructs a DocumentPermissionContext + Asynchronous coroutine to update the DocumentPermissionInstance - :param identity: Identity of the user to whom the Sync Document Permission applies. + :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: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionContext - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionContext + :returns: The updated DocumentPermissionInstance """ - return DocumentPermissionContext( - self._version, - service_sid=self._solution['service_sid'], - document_sid=self._solution['document_sid'], - identity=identity, + return await self._proxy.update_async( + read=read, + write=write, + manage=manage, ) - def __call__(self, identity): + def __repr__(self) -> str: """ - Constructs a DocumentPermissionContext + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param identity: Identity of the user to whom the Sync Document Permission applies. - :returns: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionContext - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionContext +class DocumentPermissionContext(InstanceContext): + + def __init__( + self, version: Version, service_sid: str, document_sid: str, identity: str + ): """ - return DocumentPermissionContext( - self._version, - service_sid=self._solution['service_sid'], - document_sid=self._solution['document_sid'], - identity=identity, + 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 __repr__(self): + def delete(self) -> bool: """ - Provide a friendly representation + Deletes the DocumentPermissionInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class DocumentPermissionPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, response, solution): + async def delete_async(self) -> bool: """ - Initialize the DocumentPermissionPage + Asynchronous coroutine that deletes the DocumentPermissionInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Sync Service Instance SID. - :param document_sid: Sync Document SID. - :returns: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionPage - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionPage + :returns: True if delete succeeds, False otherwise """ - super(DocumentPermissionPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def get_instance(self, payload): + def fetch(self) -> DocumentPermissionInstance: """ - Build an instance of DocumentPermissionInstance + Fetch the DocumentPermissionInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionInstance - :rtype: twilio.rest.sync.v1.service.document.document_permission.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'], + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], ) - def __repr__(self): + async def fetch_async(self) -> DocumentPermissionInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the DocumentPermissionInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched DocumentPermissionInstance """ - return '' + headers = values.of({}) -class DocumentPermissionContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Accept"] = "application/json" - def __init__(self, version, service_sid, document_sid, identity): - """ - Initialize the DocumentPermissionContext + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param document_sid: Sync Document SID or unique name. - :param identity: Identity of the user to whom the Sync Document Permission applies. + return DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) - :returns: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionContext - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionContext + def update( + self, read: bool, write: bool, manage: bool + ) -> DocumentPermissionInstance: """ - super(DocumentPermissionContext, self).__init__(version) + Update the DocumentPermissionInstance - # 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) + :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`. - def fetch(self): + :returns: The updated DocumentPermissionInstance """ - Fetch a DocumentPermissionInstance - :returns: Fetched DocumentPermissionInstance - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionInstance - """ - params = values.of({}) + 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" - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], ) - def delete(self): + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> DocumentPermissionInstance: """ - Deletes the DocumentPermissionInstance + Asynchronous coroutine to update the DocumentPermissionInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :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`. - def update(self, read, write, manage): + :returns: The updated DocumentPermissionInstance """ - Update the DocumentPermissionInstance - :param bool read: Read access. - :param bool write: Write access. - :param bool manage: Manage access. + 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" - :returns: Updated DocumentPermissionInstance - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionInstance - """ - data = values.of({'Read': read, 'Write': write, 'Manage': manage, }) + headers["Accept"] = "application/json" - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class DocumentPermissionInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class DocumentPermissionPage(Page): - def __init__(self, version, payload, service_sid, document_sid, identity=None): + def get_instance(self, payload: Dict[str, Any]) -> DocumentPermissionInstance: """ - Initialize the DocumentPermissionInstance + Build an instance of DocumentPermissionInstance - :returns: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionInstance - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionInstance + :param payload: Payload response from the API """ - super(DocumentPermissionInstance, self).__init__(version) + return DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + ) - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'document_sid': payload['document_sid'], - 'identity': payload['identity'], - 'read': payload['read'], - 'write': payload['write'], - 'manage': payload['manage'], - 'url': payload['url'], - } + def __repr__(self) -> str: + """ + Provide a friendly representation - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'document_sid': document_sid, - 'identity': identity or self._properties['identity'], - } + :returns: Machine friendly representation + """ + return "" - @property - def _proxy(self): + +class DocumentPermissionList(ListResource): + + def __init__(self, version: Version, service_sid: str, document_sid: str): """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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`. - :returns: DocumentPermissionContext for this DocumentPermissionInstance - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionContext """ - 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'], + 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 ) - return self._context + ) - @property - def account_sid(self): - """ - :returns: Twilio Account SID. - :rtype: unicode + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DocumentPermissionInstance]: """ - return self._properties['account_sid'] + 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. - @property - def service_sid(self): - """ - :returns: Sync Service Instance SID. - :rtype: unicode - """ - return self._properties['service_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) - @property - def document_sid(self): + :returns: Generator that will yield up to limit results """ - :returns: Sync Document SID. - :rtype: unicode + 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]: """ - return self._properties['document_sid'] + 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. - @property - def identity(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: Identity of the user to whom the Sync Document Permission applies. - :rtype: unicode + 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]: """ - return self._properties['identity'] + Lists DocumentPermissionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def read(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: Read access. - :rtype: bool + 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]: """ - return self._properties['read'] + 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. - @property - def write(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: Write access. - :rtype: bool + 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: """ - return self._properties['write'] + Retrieve a single page of DocumentPermissionInstance records from the API. + Request is executed immediately - @property - def manage(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: Manage access. - :rtype: bool + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['manage'] + Asynchronously retrieve a single page of DocumentPermissionInstance records from the API. + Request is executed immediately - @property - def url(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: URL of this Sync Document Permission. - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of DocumentPermissionInstance """ - Fetch a DocumentPermissionInstance + response = self._version.domain.twilio.request("GET", target_url) + return DocumentPermissionPage(self._version, response, self._solution) - :returns: Fetched DocumentPermissionInstance - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionInstance + async def get_page_async(self, target_url: str) -> DocumentPermissionPage: """ - return self._proxy.fetch() + 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 - def delete(self): + :returns: Page of DocumentPermissionInstance """ - Deletes the DocumentPermissionInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return DocumentPermissionPage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def get(self, identity: str) -> DocumentPermissionContext: """ - return self._proxy.delete() + Constructs a DocumentPermissionContext - def update(self, read, write, manage): + :param identity: The application-defined string that uniquely identifies the User's Document Permission resource to update. """ - Update the DocumentPermissionInstance + return DocumentPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=identity, + ) - :param bool read: Read access. - :param bool write: Write access. - :param bool manage: Manage access. + def __call__(self, identity: str) -> DocumentPermissionContext: + """ + Constructs a DocumentPermissionContext - :returns: Updated DocumentPermissionInstance - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionInstance + :param identity: The application-defined string that uniquely identifies the User's Document Permission resource to update. """ - return self._proxy.update(read, write, manage, ) + return DocumentPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=identity, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/sync/v1/service/sync_list/__init__.py b/twilio/rest/sync/v1/service/sync_list/__init__.py index 8e507d6c99..1b8e54aff8 100644 --- a/twilio/rest/sync/v1/service/sync_list/__init__.py +++ b/twilio/rest/sync/v1/service/sync_list/__init__.py @@ -1,530 +1,723 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 - +from twilio.rest.sync.v1.service.sync_list.sync_list_permission import ( + SyncListPermissionList, +) -class SyncListList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - def __init__(self, version, service_sid): - """ - Initialize the SyncListList +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") - :param Version version: Version that contains the resource - :param service_sid: The service_sid + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[SyncListContext] = None - :returns: twilio.rest.sync.v1.service.sync_list.SyncListList - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListList + @property + def _proxy(self) -> "SyncListContext": """ - super(SyncListList, self).__init__(version) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Lists'.format(**self._solution) + :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 create(self, unique_name=values.unset, ttl=values.unset): + def delete(self) -> bool: """ - Create a new SyncListInstance + Deletes the SyncListInstance - :param unicode unique_name: The unique_name - :param unicode ttl: The ttl - :returns: Newly created SyncListInstance - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({'UniqueName': unique_name, 'Ttl': ttl, }) + return self._proxy.delete() - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SyncListInstance - return SyncListInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return await self._proxy.delete_async() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.sync_list.SyncListInstance] + def fetch(self) -> "SyncListInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the SyncListInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched SyncListInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the SyncListInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.sync_list.SyncListInstance] + :returns: The fetched SyncListInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def update( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncListInstance": """ - Retrieve a single page of SyncListInstance records from the API. - Request is executed immediately + Update the SyncListInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :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: Page of SyncListInstance - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListPage + :returns: The updated SyncListInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + return self._proxy.update( + ttl=ttl, + collection_ttl=collection_ttl, ) - return SyncListPage(self._version, response, self._solution) - - def get_page(self, target_url): + async def update_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncListInstance": """ - Retrieve a specific page of SyncListInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the SyncListInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of SyncListInstance - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListPage + :returns: The updated SyncListInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + ttl=ttl, + collection_ttl=collection_ttl, ) - return SyncListPage(self._version, response, self._solution) - - def get(self, sid): + @property + def sync_list_items(self) -> SyncListItemList: """ - Constructs a SyncListContext - - :param sid: The sid - - :returns: twilio.rest.sync.v1.service.sync_list.SyncListContext - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListContext + Access the sync_list_items """ - return SyncListContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.sync_list_items - def __call__(self, sid): + @property + def sync_list_permissions(self) -> SyncListPermissionList: """ - Constructs a SyncListContext - - :param sid: The sid - - :returns: twilio.rest.sync.v1.service.sync_list.SyncListContext - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListContext + Access the sync_list_permissions """ - return SyncListContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.sync_list_permissions - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class SyncListPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class SyncListContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the SyncListPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid + Initialize the SyncListContext - :returns: twilio.rest.sync.v1.service.sync_list.SyncListPage - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListPage + :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(SyncListPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Lists/{sid}".format(**self._solution) - def get_instance(self, payload): + self._sync_list_items: Optional[SyncListItemList] = None + self._sync_list_permissions: Optional[SyncListPermissionList] = None + + def delete(self) -> bool: """ - Build an instance of SyncListInstance + Deletes the SyncListInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.sync.v1.service.sync_list.SyncListInstance - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListInstance + :returns: True if delete succeeds, False otherwise """ - return SyncListInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the SyncListInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class SyncListContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, service_sid, sid): + def fetch(self) -> SyncListInstance: """ - Initialize the SyncListContext + Fetch the SyncListInstance - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: The sid - :returns: twilio.rest.sync.v1.service.sync_list.SyncListContext - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListContext + :returns: The fetched SyncListInstance """ - super(SyncListContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Lists/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._sync_list_items = None - self._sync_list_permissions = None + 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"], + ) - def fetch(self): + async def fetch_async(self) -> SyncListInstance: """ - Fetch a SyncListInstance + Asynchronous coroutine to fetch the SyncListInstance - :returns: Fetched SyncListInstance - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListInstance + + :returns: The fetched SyncListInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + def update( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListInstance: """ - Deletes the SyncListInstance + Update the SyncListInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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._version.delete('delete', self._uri) - def update(self, ttl=values.unset): + 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: """ - Update the SyncListInstance + Asynchronous coroutine to update the SyncListInstance - :param unicode ttl: The ttl + :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: Updated SyncListInstance - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListInstance + :returns: The updated SyncListInstance """ - data = values.of({'Ttl': ttl, }) - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) @property - def sync_list_items(self): + def sync_list_items(self) -> SyncListItemList: """ Access the sync_list_items - - :returns: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemList - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemList """ if self._sync_list_items is None: self._sync_list_items = SyncListItemList( self._version, - service_sid=self._solution['service_sid'], - list_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) return self._sync_list_items @property - def sync_list_permissions(self): + def sync_list_permissions(self) -> SyncListPermissionList: """ Access the sync_list_permissions - - :returns: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionList - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionList """ if self._sync_list_permissions is None: self._sync_list_permissions = SyncListPermissionList( self._version, - service_sid=self._solution['service_sid'], - list_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) return self._sync_list_permissions - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class SyncListInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the SyncListInstance - - :returns: twilio.rest.sync.v1.service.sync_list.SyncListInstance - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListInstance - """ - super(SyncListInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'unique_name': payload['unique_name'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'url': payload['url'], - 'links': payload['links'], - 'revision': payload['revision'], - 'date_expires': deserialize.iso8601_datetime(payload['date_expires']), - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'created_by': payload['created_by'], - } - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } +class SyncListPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> SyncListInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of SyncListInstance - :returns: SyncListContext for this SyncListInstance - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = SyncListContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + return SyncListInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def sid(self): + def __repr__(self) -> str: """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def unique_name(self): - """ - :returns: The unique_name - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['unique_name'] + return "" - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def service_sid(self): +class SyncListList(ListResource): + + def __init__(self, version: Version, service_sid: str): """ - :returns: The service_sid - :rtype: unicode + 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. + """ - return self._properties['service_sid'] + super().__init__(version) - @property - def url(self): + # 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: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] - @property - def links(self): + 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: """ - :returns: The links - :rtype: unicode + 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 """ - return self._properties['links'] - @property - def revision(self): + 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]: """ - :returns: The revision - :rtype: unicode + 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 """ - return self._properties['revision'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def date_expires(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SyncListInstance]: """ - :returns: The date_expires - :rtype: datetime + 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 """ - return self._properties['date_expires'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def date_created(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncListInstance]: """ - :returns: The date_created - :rtype: datetime + 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 self._properties['date_created'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def date_updated(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncListInstance]: """ - :returns: The date_updated - :rtype: datetime + 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 self._properties['date_updated'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def created_by(self): + 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: """ - :returns: The created_by - :rtype: unicode + 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 """ - return self._properties['created_by'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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) - def fetch(self): + 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: """ - Fetch a SyncListInstance + Asynchronously retrieve a single page of SyncListInstance records from the API. + Request is executed immediately - :returns: Fetched SyncListInstance - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListInstance + :param page_token: PageToken provided by the API + :param page_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 """ - return self._proxy.fetch() + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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 delete(self): + def get_page(self, target_url: str) -> SyncListPage: """ - Deletes the SyncListInstance + Retrieve a specific page of SyncListInstance records from the API. + Request is executed immediately - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncListInstance """ - return self._proxy.delete() + response = self._version.domain.twilio.request("GET", target_url) + return SyncListPage(self._version, response, self._solution) - def update(self, ttl=values.unset): + async def get_page_async(self, target_url: str) -> SyncListPage: """ - Update the SyncListInstance + Asynchronously retrieve a specific page of SyncListInstance records from the API. + Request is executed immediately - :param unicode ttl: The ttl + :param target_url: API-generated URL for the requested results page - :returns: Updated SyncListInstance - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListInstance + :returns: Page of SyncListInstance """ - return self._proxy.update(ttl=ttl, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncListPage(self._version, response, self._solution) - @property - def sync_list_items(self): + def get(self, sid: str) -> SyncListContext: """ - Access the sync_list_items + Constructs a SyncListContext - :returns: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemList - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemList + :param sid: The SID of the Sync List resource to update. Can be the Sync List resource's `sid` or its `unique_name`. """ - return self._proxy.sync_list_items + return SyncListContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - @property - def sync_list_permissions(self): + def __call__(self, sid: str) -> SyncListContext: """ - Access the sync_list_permissions + Constructs a SyncListContext - :returns: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionList - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionList + :param sid: The SID of the Sync List resource to update. Can be the Sync List resource's `sid` or its `unique_name`. """ - return self._proxy.sync_list_permissions + return SyncListContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 index 639eac5d77..61783aa525 100644 --- a/twilio/rest/sync/v1/service/sync_list/sync_list_item.py +++ b/twilio/rest/sync/v1/service/sync_list/sync_list_item.py @@ -1,532 +1,835 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 SyncListItemList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class SyncListItemInstance(InstanceResource): - def __init__(self, version, service_sid, list_sid): - """ - Initialize the SyncListItemList + class QueryFromBoundType(object): + INCLUSIVE = "inclusive" + EXCLUSIVE = "exclusive" - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param list_sid: The list_sid + class QueryResultOrder(object): + ASC = "asc" + DESC = "desc" - :returns: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemList - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemList - """ - super(SyncListItemList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'service_sid': service_sid, 'list_sid': list_sid, } - self._uri = '/Services/{service_sid}/Lists/{list_sid}/Items'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "list_sid": list_sid, + "index": index or self.index, + } + self._context: Optional[SyncListItemContext] = None - def create(self, data, ttl=values.unset): + @property + def _proxy(self) -> "SyncListItemContext": """ - Create a new SyncListItemInstance + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param dict data: The data - :param unicode ttl: The ttl + :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 - :returns: Newly created SyncListItemInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemInstance + def delete(self, if_match: Union[str, object] = values.unset) -> bool: """ - data = values.of({'Data': serialize.object(data), 'Ttl': ttl, }) + Deletes the SyncListItemInstance - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + :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). - return SyncListItemInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + if_match=if_match, ) - def stream(self, order=values.unset, from_=values.unset, bounds=values.unset, - limit=None, page_size=None): + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: """ - 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. + Asynchronous coroutine that deletes the SyncListItemInstance - :param SyncListItemInstance.QueryResultOrder order: The order - :param unicode from_: The from - :param SyncListItemInstance.QueryFromBoundType bounds: The bounds - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :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: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemInstance] + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async( + if_match=if_match, + ) + + def fetch(self) -> "SyncListItemInstance": + """ + Fetch the SyncListItemInstance - page = self.page(order=order, from_=from_, bounds=bounds, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched SyncListItemInstance + """ + return self._proxy.fetch() - def list(self, order=values.unset, from_=values.unset, bounds=values.unset, - limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the SyncListItemInstance - :param SyncListItemInstance.QueryResultOrder order: The order - :param unicode from_: The from - :param SyncListItemInstance.QueryFromBoundType bounds: The bounds - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemInstance] + :returns: The fetched SyncListItemInstance """ - return list(self.stream(order=order, from_=from_, bounds=bounds, limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, order=values.unset, from_=values.unset, bounds=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + 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": """ - Retrieve a single page of SyncListItemInstance records from the API. - Request is executed immediately + Update the SyncListItemInstance - :param SyncListItemInstance.QueryResultOrder order: The order - :param unicode from_: The from - :param SyncListItemInstance.QueryFromBoundType bounds: The bounds - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :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: Page of SyncListItemInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemPage + :returns: The updated SyncListItemInstance """ - params = values.of({ - 'Order': order, - 'From': from_, - 'Bounds': bounds, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + return self._proxy.update( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, ) - return SyncListItemPage(self._version, response, self._solution) - - def get_page(self, target_url): + 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": """ - Retrieve a specific page of SyncListItemInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the SyncListItemInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of SyncListItemInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemPage + :returns: The updated SyncListItemInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, ) - return SyncListItemPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, index): + :returns: Machine friendly representation """ - Constructs a SyncListItemContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param index: The index - :returns: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemContext - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemContext +class SyncListItemContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, list_sid: str, index: int): """ - return SyncListItemContext( - self._version, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - index=index, + 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 __call__(self, index): + def delete(self, if_match: Union[str, object] = values.unset) -> bool: """ - Constructs a SyncListItemContext + Deletes the SyncListItemInstance - :param index: The index + :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: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemContext - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemContext + :returns: True if delete succeeds, False otherwise """ - return SyncListItemContext( - self._version, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - index=index, + headers = values.of( + { + "If-Match": if_match, + } ) - def __repr__(self): + 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: """ - Provide a friendly representation + Asynchronous coroutine that deletes the SyncListItemInstance - :returns: Machine friendly representation - :rtype: str + :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 '' + headers = values.of( + { + "If-Match": if_match, + } + ) + headers = values.of({}) -class SyncListItemPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> SyncListItemInstance: """ - Initialize the SyncListItemPage + Fetch the SyncListItemInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :param list_sid: The list_sid - :returns: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemPage - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemPage + :returns: The fetched SyncListItemInstance """ - super(SyncListItemPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): - """ - Build an instance of SyncListItemInstance + headers["Accept"] = "application/json" - :param dict payload: Payload response from the API + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemInstance - """ return SyncListItemInstance( self._version, payload, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], ) - def __repr__(self): + async def fetch_async(self) -> SyncListItemInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the SyncListItemInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched SyncListItemInstance """ - return '' + headers = values.of({}) -class SyncListItemContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Accept"] = "application/json" - def __init__(self, version, service_sid, list_sid, index): - """ - Initialize the SyncListItemContext + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param list_sid: The list_sid - :param index: The index + return SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], + ) - :returns: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemContext - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemContext + 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: """ - super(SyncListItemContext, self).__init__(version) + Update the SyncListItemInstance - # 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) + :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. - def fetch(self): + :returns: The updated SyncListItemInstance """ - Fetch a SyncListItemInstance - :returns: Fetched SyncListItemInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemInstance - """ - params = values.of({}) + 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 - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], ) - def delete(self): - """ - Deletes the SyncListItemInstance + 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({}) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match - def update(self, data=values.unset, ttl=values.unset): - """ - Update the SyncListItemInstance - - :param dict data: The data - :param unicode ttl: The ttl + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: Updated SyncListItemInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemInstance - """ - data = values.of({'Data': serialize.object(data), 'Ttl': ttl, }) + headers["Accept"] = "application/json" - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class SyncListItemInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class SyncListItemPage(Page): - class QueryResultOrder(object): - ASC = "asc" - DESC = "desc" + def get_instance(self, payload: Dict[str, Any]) -> SyncListItemInstance: + """ + Build an instance of SyncListItemInstance - class QueryFromBoundType(object): - INCLUSIVE = "inclusive" - EXCLUSIVE = "exclusive" + :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 __init__(self, version, payload, service_sid, list_sid, index=None): + def __repr__(self) -> str: """ - Initialize the SyncListItemInstance + Provide a friendly representation - :returns: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemInstance + :returns: Machine friendly representation """ - super(SyncListItemInstance, self).__init__(version) + return "" - # Marshaled Properties - self._properties = { - 'index': deserialize.integer(payload['index']), - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'list_sid': payload['list_sid'], - 'url': payload['url'], - 'revision': payload['revision'], - 'data': payload['data'], - 'date_expires': deserialize.iso8601_datetime(payload['date_expires']), - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'created_by': payload['created_by'], - } - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'list_sid': list_sid, - 'index': index or self._properties['index'], - } +class SyncListItemList(ListResource): - @property - def _proxy(self): + def __init__(self, version: Version, service_sid: str, list_sid: str): """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Initialize the SyncListItemList - :returns: SyncListItemContext for this SyncListItemInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemContext - """ - 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 + :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`. - @property - def index(self): - """ - :returns: The index - :rtype: unicode """ - return self._properties['index'] + super().__init__(version) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + # Path Solution + self._solution = { + "service_sid": service_sid, + "list_sid": list_sid, + } + self._uri = "/Services/{service_sid}/Lists/{list_sid}/Items".format( + **self._solution + ) - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode + 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: """ - return self._properties['service_sid'] + Create the SyncListItemInstance - @property - def list_sid(self): - """ - :returns: The list_sid - :rtype: unicode - """ - return self._properties['list_sid'] + :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. - @property - def url(self): + :returns: The created SyncListItemInstance """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - @property - def revision(self): + 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: """ - :returns: The revision - :rtype: unicode + 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 """ - return self._properties['revision'] - @property - def data(self): + 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]: """ - :returns: The data - :rtype: dict + 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 """ - return self._properties['data'] + limits = self._version.read_limits(limit, page_size) + page = self.page( + order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] + ) - @property - def date_expires(self): + 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]: """ - :returns: The date_expires - :rtype: datetime + 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 """ - return self._properties['date_expires'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] + ) - @property - def date_created(self): + 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]: """ - :returns: The date_created - :rtype: datetime + 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]: """ - return self._properties['date_created'] + 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. - @property - def date_updated(self): + :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: """ - :returns: The date_updated - :rtype: datetime + 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 """ - return self._properties['date_updated'] + data = values.of( + { + "Order": order, + "From": from_, + "Bounds": bounds, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def created_by(self): + headers = values.of({"Content-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 """ - :returns: The created_by - :rtype: unicode + 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: """ - return self._properties['created_by'] + 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 - def fetch(self): + :returns: Page of SyncListItemInstance """ - Fetch a SyncListItemInstance + response = self._version.domain.twilio.request("GET", target_url) + return SyncListItemPage(self._version, response, self._solution) - :returns: Fetched SyncListItemInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemInstance + async def get_page_async(self, target_url: str) -> SyncListItemPage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of SyncListItemInstance records from the API. + Request is executed immediately - def delete(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncListItemInstance """ - Deletes the SyncListItemInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncListItemPage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def get(self, index: int) -> SyncListItemContext: """ - return self._proxy.delete() + Constructs a SyncListItemContext - def update(self, data=values.unset, ttl=values.unset): + :param index: The index of the Sync List Item resource to update. """ - Update the SyncListItemInstance + return SyncListItemContext( + self._version, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=index, + ) - :param dict data: The data - :param unicode ttl: The ttl + def __call__(self, index: int) -> SyncListItemContext: + """ + Constructs a SyncListItemContext - :returns: Updated SyncListItemInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemInstance + :param index: The index of the Sync List Item resource to update. """ - return self._proxy.update(data=data, ttl=ttl, ) + return SyncListItemContext( + self._version, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=index, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 index b09e3795f0..f1eb853468 100644 --- a/twilio/rest/sync/v1/service/sync_list/sync_list_permission.py +++ b/twilio/rest/sync/v1/service/sync_list/sync_list_permission.py @@ -1,453 +1,617 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import values +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 SyncListPermissionList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +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 - def __init__(self, version, service_sid, list_sid): + @property + def _proxy(self) -> "SyncListPermissionContext": """ - Initialize the SyncListPermissionList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: Sync Service Instance SID. - :param list_sid: Sync List SID. + :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 - :returns: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionList - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionList + def delete(self) -> bool: """ - super(SyncListPermissionList, self).__init__(version) + Deletes the SyncListPermissionInstance - # 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=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the SyncListPermissionInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the SyncListPermissionInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance] + :returns: The fetched SyncListPermissionInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_async(self) -> "SyncListPermissionInstance": """ - Retrieve a single page of SyncListPermissionInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the SyncListPermissionInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of SyncListPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionPage + :returns: The fetched SyncListPermissionInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_async() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return SyncListPermissionPage(self._version, response, self._solution) - - def get_page(self, target_url): + def update( + self, read: bool, write: bool, manage: bool + ) -> "SyncListPermissionInstance": """ - Retrieve a specific page of SyncListPermissionInstance records from the API. - Request is executed immediately + Update the SyncListPermissionInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of SyncListPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionPage + :returns: The updated SyncListPermissionInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + read=read, + write=write, + manage=manage, ) - return SyncListPermissionPage(self._version, response, self._solution) - - def get(self, identity): + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> "SyncListPermissionInstance": """ - Constructs a SyncListPermissionContext + Asynchronous coroutine to update the SyncListPermissionInstance - :param identity: Identity of the user to whom the Sync List Permission applies. + :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: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionContext - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionContext + :returns: The updated SyncListPermissionInstance """ - return SyncListPermissionContext( - self._version, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - identity=identity, + return await self._proxy.update_async( + read=read, + write=write, + manage=manage, ) - def __call__(self, identity): + def __repr__(self) -> str: """ - Constructs a SyncListPermissionContext + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param identity: Identity of the user to whom the Sync List Permission applies. - :returns: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionContext - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionContext +class SyncListPermissionContext(InstanceContext): + + def __init__( + self, version: Version, service_sid: str, list_sid: str, identity: str + ): """ - return SyncListPermissionContext( - self._version, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - identity=identity, + 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 __repr__(self): + def delete(self) -> bool: """ - Provide a friendly representation + Deletes the SyncListPermissionInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class SyncListPermissionPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, response, solution): + async def delete_async(self) -> bool: """ - Initialize the SyncListPermissionPage + Asynchronous coroutine that deletes the SyncListPermissionInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Sync Service Instance SID. - :param list_sid: Sync List SID. - :returns: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionPage - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionPage + :returns: True if delete succeeds, False otherwise """ - super(SyncListPermissionPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def get_instance(self, payload): + def fetch(self) -> SyncListPermissionInstance: """ - Build an instance of SyncListPermissionInstance + Fetch the SyncListPermissionInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.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'], + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], ) - def __repr__(self): + async def fetch_async(self) -> SyncListPermissionInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the SyncListPermissionInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched SyncListPermissionInstance """ - return '' + headers = values.of({}) -class SyncListPermissionContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Accept"] = "application/json" - def __init__(self, version, service_sid, list_sid, identity): - """ - Initialize the SyncListPermissionContext + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param list_sid: Sync List SID or unique name. - :param identity: Identity of the user to whom the Sync List Permission applies. + return SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) - :returns: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionContext - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionContext + def update( + self, read: bool, write: bool, manage: bool + ) -> SyncListPermissionInstance: """ - super(SyncListPermissionContext, self).__init__(version) + Update the SyncListPermissionInstance - # 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) + :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`. - def fetch(self): + :returns: The updated SyncListPermissionInstance """ - Fetch a SyncListPermissionInstance - :returns: Fetched SyncListPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance - """ - params = values.of({}) + 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" - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], ) - def delete(self): + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> SyncListPermissionInstance: """ - Deletes the SyncListPermissionInstance + Asynchronous coroutine to update the SyncListPermissionInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :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`. - def update(self, read, write, manage): + :returns: The updated SyncListPermissionInstance """ - Update the SyncListPermissionInstance - :param bool read: Read access. - :param bool write: Write access. - :param bool manage: Manage access. + 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" - :returns: Updated SyncListPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance - """ - data = values.of({'Read': read, 'Write': write, 'Manage': manage, }) + headers["Accept"] = "application/json" - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class SyncListPermissionInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class SyncListPermissionPage(Page): - def __init__(self, version, payload, service_sid, list_sid, identity=None): + def get_instance(self, payload: Dict[str, Any]) -> SyncListPermissionInstance: """ - Initialize the SyncListPermissionInstance + Build an instance of SyncListPermissionInstance - :returns: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance + :param payload: Payload response from the API """ - super(SyncListPermissionInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'list_sid': payload['list_sid'], - 'identity': payload['identity'], - 'read': payload['read'], - 'write': payload['write'], - 'manage': payload['manage'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'list_sid': list_sid, - 'identity': identity or self._properties['identity'], - } + return SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + ) - @property - def _proxy(self): + def __repr__(self) -> str: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Provide a friendly representation - :returns: SyncListPermissionContext for this SyncListPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionContext + :returns: Machine friendly representation """ - 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 + return "" - @property - def account_sid(self): - """ - :returns: Twilio Account SID. - :rtype: unicode + +class SyncListPermissionList(ListResource): + + def __init__(self, version: Version, service_sid: str, list_sid: str): """ - return self._properties['account_sid'] + 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`. - @property - def service_sid(self): """ - :returns: Sync Service Instance SID. - :rtype: unicode + 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]: """ - return self._properties['service_sid'] + 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. - @property - def list_sid(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: Sync List SID. - :rtype: unicode + 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]: """ - return self._properties['list_sid'] + 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. - @property - def identity(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: Identity of the user to whom the Sync List Permission applies. - :rtype: unicode + 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]: """ - return self._properties['identity'] + Lists SyncListPermissionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def read(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: Read access. - :rtype: bool + 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]: """ - return self._properties['read'] + 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. - @property - def write(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: Write access. - :rtype: bool + 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: """ - return self._properties['write'] + Retrieve a single page of SyncListPermissionInstance records from the API. + Request is executed immediately - @property - def manage(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: Manage access. - :rtype: bool + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['manage'] + Asynchronously retrieve a single page of SyncListPermissionInstance records from the API. + Request is executed immediately - @property - def url(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: URL of this Sync List Permission. - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of SyncListPermissionInstance """ - Fetch a SyncListPermissionInstance + response = self._version.domain.twilio.request("GET", target_url) + return SyncListPermissionPage(self._version, response, self._solution) - :returns: Fetched SyncListPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance + async def get_page_async(self, target_url: str) -> SyncListPermissionPage: """ - return self._proxy.fetch() + 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 - def delete(self): + :returns: Page of SyncListPermissionInstance """ - Deletes the SyncListPermissionInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncListPermissionPage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def get(self, identity: str) -> SyncListPermissionContext: """ - return self._proxy.delete() + Constructs a SyncListPermissionContext - def update(self, read, write, manage): + :param identity: The application-defined string that uniquely identifies the User's Sync List Permission resource to update. """ - Update the SyncListPermissionInstance + return SyncListPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=identity, + ) - :param bool read: Read access. - :param bool write: Write access. - :param bool manage: Manage access. + def __call__(self, identity: str) -> SyncListPermissionContext: + """ + Constructs a SyncListPermissionContext - :returns: Updated SyncListPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance + :param identity: The application-defined string that uniquely identifies the User's Sync List Permission resource to update. """ - return self._proxy.update(read, write, manage, ) + return SyncListPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=identity, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/sync/v1/service/sync_map/__init__.py b/twilio/rest/sync/v1/service/sync_map/__init__.py index 0dd366b5df..c6bb1ce556 100644 --- a/twilio/rest/sync/v1/service/sync_map/__init__.py +++ b/twilio/rest/sync/v1/service/sync_map/__init__.py @@ -1,530 +1,723 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 - +from twilio.rest.sync.v1.service.sync_map.sync_map_permission import ( + SyncMapPermissionList, +) -class SyncMapList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - def __init__(self, version, service_sid): - """ - Initialize the SyncMapList +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") - :param Version version: Version that contains the resource - :param service_sid: The service_sid + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[SyncMapContext] = None - :returns: twilio.rest.sync.v1.service.sync_map.SyncMapList - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapList + @property + def _proxy(self) -> "SyncMapContext": """ - super(SyncMapList, self).__init__(version) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Maps'.format(**self._solution) + :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 create(self, unique_name=values.unset, ttl=values.unset): + def delete(self) -> bool: """ - Create a new SyncMapInstance + Deletes the SyncMapInstance - :param unicode unique_name: The unique_name - :param unicode ttl: The ttl - :returns: Newly created SyncMapInstance - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({'UniqueName': unique_name, 'Ttl': ttl, }) + return self._proxy.delete() - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SyncMapInstance - return SyncMapInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return await self._proxy.delete_async() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.sync_map.SyncMapInstance] + def fetch(self) -> "SyncMapInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the SyncMapInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched SyncMapInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the SyncMapInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.sync_map.SyncMapInstance] + :returns: The fetched SyncMapInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def update( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncMapInstance": """ - Retrieve a single page of SyncMapInstance records from the API. - Request is executed immediately + Update the SyncMapInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :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: Page of SyncMapInstance - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapPage + :returns: The updated SyncMapInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + return self._proxy.update( + ttl=ttl, + collection_ttl=collection_ttl, ) - return SyncMapPage(self._version, response, self._solution) - - def get_page(self, target_url): + async def update_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncMapInstance": """ - Retrieve a specific page of SyncMapInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the SyncMapInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of SyncMapInstance - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapPage + :returns: The updated SyncMapInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + ttl=ttl, + collection_ttl=collection_ttl, ) - return SyncMapPage(self._version, response, self._solution) - - def get(self, sid): + @property + def sync_map_items(self) -> SyncMapItemList: """ - Constructs a SyncMapContext - - :param sid: The sid - - :returns: twilio.rest.sync.v1.service.sync_map.SyncMapContext - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapContext + Access the sync_map_items """ - return SyncMapContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.sync_map_items - def __call__(self, sid): + @property + def sync_map_permissions(self) -> SyncMapPermissionList: """ - Constructs a SyncMapContext - - :param sid: The sid - - :returns: twilio.rest.sync.v1.service.sync_map.SyncMapContext - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapContext + Access the sync_map_permissions """ - return SyncMapContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.sync_map_permissions - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class SyncMapPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class SyncMapContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the SyncMapPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid + Initialize the SyncMapContext - :returns: twilio.rest.sync.v1.service.sync_map.SyncMapPage - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapPage + :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(SyncMapPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Maps/{sid}".format(**self._solution) - def get_instance(self, payload): + self._sync_map_items: Optional[SyncMapItemList] = None + self._sync_map_permissions: Optional[SyncMapPermissionList] = None + + def delete(self) -> bool: """ - Build an instance of SyncMapInstance + Deletes the SyncMapInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.sync.v1.service.sync_map.SyncMapInstance - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapInstance + :returns: True if delete succeeds, False otherwise """ - return SyncMapInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the SyncMapInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class SyncMapContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, service_sid, sid): + def fetch(self) -> SyncMapInstance: """ - Initialize the SyncMapContext + Fetch the SyncMapInstance - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: The sid - :returns: twilio.rest.sync.v1.service.sync_map.SyncMapContext - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapContext + :returns: The fetched SyncMapInstance """ - super(SyncMapContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Maps/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._sync_map_items = None - self._sync_map_permissions = None + 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"], + ) - def fetch(self): + async def fetch_async(self) -> SyncMapInstance: """ - Fetch a SyncMapInstance + Asynchronous coroutine to fetch the SyncMapInstance - :returns: Fetched SyncMapInstance - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapInstance + + :returns: The fetched SyncMapInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + def update( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapInstance: """ - Deletes the SyncMapInstance + Update the SyncMapInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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._version.delete('delete', self._uri) - def update(self, ttl=values.unset): + 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: """ - Update the SyncMapInstance + Asynchronous coroutine to update the SyncMapInstance - :param unicode ttl: The ttl + :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: Updated SyncMapInstance - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapInstance + :returns: The updated SyncMapInstance """ - data = values.of({'Ttl': ttl, }) - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) @property - def sync_map_items(self): + def sync_map_items(self) -> SyncMapItemList: """ Access the sync_map_items - - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemList - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemList """ if self._sync_map_items is None: self._sync_map_items = SyncMapItemList( self._version, - service_sid=self._solution['service_sid'], - map_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) return self._sync_map_items @property - def sync_map_permissions(self): + def sync_map_permissions(self) -> SyncMapPermissionList: """ Access the sync_map_permissions - - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionList - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionList """ if self._sync_map_permissions is None: self._sync_map_permissions = SyncMapPermissionList( self._version, - service_sid=self._solution['service_sid'], - map_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) return self._sync_map_permissions - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class SyncMapInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the SyncMapInstance - - :returns: twilio.rest.sync.v1.service.sync_map.SyncMapInstance - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapInstance - """ - super(SyncMapInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'unique_name': payload['unique_name'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'url': payload['url'], - 'links': payload['links'], - 'revision': payload['revision'], - 'date_expires': deserialize.iso8601_datetime(payload['date_expires']), - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'created_by': payload['created_by'], - } - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } +class SyncMapPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> SyncMapInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of SyncMapInstance - :returns: SyncMapContext for this SyncMapInstance - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = SyncMapContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + return SyncMapInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def sid(self): + def __repr__(self) -> str: """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def unique_name(self): - """ - :returns: The unique_name - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['unique_name'] + return "" - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def service_sid(self): +class SyncMapList(ListResource): + + def __init__(self, version: Version, service_sid: str): """ - :returns: The service_sid - :rtype: unicode + 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. + """ - return self._properties['service_sid'] + super().__init__(version) - @property - def url(self): + # 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: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] - @property - def links(self): + 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: """ - :returns: The links - :rtype: unicode + 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 """ - return self._properties['links'] - @property - def revision(self): + 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]: """ - :returns: The revision - :rtype: unicode + 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 """ - return self._properties['revision'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def date_expires(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SyncMapInstance]: """ - :returns: The date_expires - :rtype: datetime + 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 """ - return self._properties['date_expires'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def date_created(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncMapInstance]: """ - :returns: The date_created - :rtype: datetime + 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 self._properties['date_created'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def date_updated(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncMapInstance]: """ - :returns: The date_updated - :rtype: datetime + 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 self._properties['date_updated'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def created_by(self): + 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: """ - :returns: The created_by - :rtype: unicode + 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 """ - return self._properties['created_by'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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) - def fetch(self): + 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: """ - Fetch a SyncMapInstance + Asynchronously retrieve a single page of SyncMapInstance records from the API. + Request is executed immediately - :returns: Fetched SyncMapInstance - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapInstance + :param page_token: PageToken provided by the API + :param page_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 """ - return self._proxy.fetch() + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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 delete(self): + def get_page(self, target_url: str) -> SyncMapPage: """ - Deletes the SyncMapInstance + Retrieve a specific page of SyncMapInstance records from the API. + Request is executed immediately - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncMapInstance """ - return self._proxy.delete() + response = self._version.domain.twilio.request("GET", target_url) + return SyncMapPage(self._version, response, self._solution) - def update(self, ttl=values.unset): + async def get_page_async(self, target_url: str) -> SyncMapPage: """ - Update the SyncMapInstance + Asynchronously retrieve a specific page of SyncMapInstance records from the API. + Request is executed immediately - :param unicode ttl: The ttl + :param target_url: API-generated URL for the requested results page - :returns: Updated SyncMapInstance - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapInstance + :returns: Page of SyncMapInstance """ - return self._proxy.update(ttl=ttl, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncMapPage(self._version, response, self._solution) - @property - def sync_map_items(self): + def get(self, sid: str) -> SyncMapContext: """ - Access the sync_map_items + Constructs a SyncMapContext - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemList - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemList + :param sid: The SID of the Sync Map resource to update. Can be the Sync Map's `sid` or its `unique_name`. """ - return self._proxy.sync_map_items + return SyncMapContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - @property - def sync_map_permissions(self): + def __call__(self, sid: str) -> SyncMapContext: """ - Access the sync_map_permissions + Constructs a SyncMapContext - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionList - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionList + :param sid: The SID of the Sync Map resource to update. Can be the Sync Map's `sid` or its `unique_name`. """ - return self._proxy.sync_map_permissions + return SyncMapContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 index ec5759c6cb..4939694026 100644 --- a/twilio/rest/sync/v1/service/sync_map/sync_map_item.py +++ b/twilio/rest/sync/v1/service/sync_map/sync_map_item.py @@ -1,533 +1,841 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 SyncMapItemList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class SyncMapItemInstance(InstanceResource): - def __init__(self, version, service_sid, map_sid): - """ - Initialize the SyncMapItemList + class QueryFromBoundType(object): + INCLUSIVE = "inclusive" + EXCLUSIVE = "exclusive" - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param map_sid: The map_sid + class QueryResultOrder(object): + ASC = "asc" + DESC = "desc" - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemList - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemList - """ - super(SyncMapItemList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'service_sid': service_sid, 'map_sid': map_sid, } - self._uri = '/Services/{service_sid}/Maps/{map_sid}/Items'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "map_sid": map_sid, + "key": key or self.key, + } + self._context: Optional[SyncMapItemContext] = None - def create(self, key, data, ttl=values.unset): + @property + def _proxy(self) -> "SyncMapItemContext": """ - Create a new SyncMapItemInstance + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param unicode key: The key - :param dict data: The data - :param unicode ttl: The ttl + :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 - :returns: Newly created SyncMapItemInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemInstance + def delete(self, if_match: Union[str, object] = values.unset) -> bool: """ - data = values.of({'Key': key, 'Data': serialize.object(data), 'Ttl': ttl, }) + Deletes the SyncMapItemInstance - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + :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). - return SyncMapItemInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + if_match=if_match, ) - def stream(self, order=values.unset, from_=values.unset, bounds=values.unset, - limit=None, page_size=None): + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: """ - 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. + Asynchronous coroutine that deletes the SyncMapItemInstance - :param SyncMapItemInstance.QueryResultOrder order: The order - :param unicode from_: The from - :param SyncMapItemInstance.QueryFromBoundType bounds: The bounds - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :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: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemInstance] + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async( + if_match=if_match, + ) + + def fetch(self) -> "SyncMapItemInstance": + """ + Fetch the SyncMapItemInstance - page = self.page(order=order, from_=from_, bounds=bounds, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched SyncMapItemInstance + """ + return self._proxy.fetch() - def list(self, order=values.unset, from_=values.unset, bounds=values.unset, - limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the SyncMapItemInstance - :param SyncMapItemInstance.QueryResultOrder order: The order - :param unicode from_: The from - :param SyncMapItemInstance.QueryFromBoundType bounds: The bounds - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemInstance] + :returns: The fetched SyncMapItemInstance """ - return list(self.stream(order=order, from_=from_, bounds=bounds, limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, order=values.unset, from_=values.unset, bounds=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + 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": """ - Retrieve a single page of SyncMapItemInstance records from the API. - Request is executed immediately + Update the SyncMapItemInstance - :param SyncMapItemInstance.QueryResultOrder order: The order - :param unicode from_: The from - :param SyncMapItemInstance.QueryFromBoundType bounds: The bounds - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :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: Page of SyncMapItemInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemPage + :returns: The updated SyncMapItemInstance """ - params = values.of({ - 'Order': order, - 'From': from_, - 'Bounds': bounds, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + return self._proxy.update( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, ) - return SyncMapItemPage(self._version, response, self._solution) - - def get_page(self, target_url): + 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": """ - Retrieve a specific page of SyncMapItemInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the SyncMapItemInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of SyncMapItemInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemPage + :returns: The updated SyncMapItemInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, ) - return SyncMapItemPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, key): + :returns: Machine friendly representation """ - Constructs a SyncMapItemContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - :param key: The key +class SyncMapItemContext(InstanceContext): - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemContext - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemContext + def __init__(self, version: Version, service_sid: str, map_sid: str, key: str): """ - return SyncMapItemContext( - self._version, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - key=key, + 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 __call__(self, key): + def delete(self, if_match: Union[str, object] = values.unset) -> bool: """ - Constructs a SyncMapItemContext + Deletes the SyncMapItemInstance - :param key: The key + :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: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemContext - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemContext + :returns: True if delete succeeds, False otherwise """ - return SyncMapItemContext( - self._version, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - key=key, + headers = values.of( + { + "If-Match": if_match, + } ) - def __repr__(self): + 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: """ - Provide a friendly representation + Asynchronous coroutine that deletes the SyncMapItemInstance - :returns: Machine friendly representation - :rtype: str + :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 '' + headers = values.of( + { + "If-Match": if_match, + } + ) + headers = values.of({}) -class SyncMapItemPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> SyncMapItemInstance: """ - Initialize the SyncMapItemPage + Fetch the SyncMapItemInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The service_sid - :param map_sid: The map_sid - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemPage - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemPage + :returns: The fetched SyncMapItemInstance """ - super(SyncMapItemPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): - """ - Build an instance of SyncMapItemInstance + headers["Accept"] = "application/json" - :param dict payload: Payload response from the API + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemInstance - """ return SyncMapItemInstance( self._version, payload, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], ) - def __repr__(self): + async def fetch_async(self) -> SyncMapItemInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the SyncMapItemInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched SyncMapItemInstance """ - return '' + headers = values.of({}) -class SyncMapItemContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Accept"] = "application/json" - def __init__(self, version, service_sid, map_sid, key): - """ - Initialize the SyncMapItemContext + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param map_sid: The map_sid - :param key: The key + return SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], + ) - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemContext - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemContext + 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: """ - super(SyncMapItemContext, self).__init__(version) + Update the SyncMapItemInstance - # 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) + :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. - def fetch(self): + :returns: The updated SyncMapItemInstance """ - Fetch a SyncMapItemInstance - :returns: Fetched SyncMapItemInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemInstance - """ - params = values.of({}) + data = values.of( + { + "Data": serialize.object(data), + "Ttl": ttl, + "ItemTtl": item_ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], ) - def delete(self): - """ - Deletes the SyncMapItemInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + 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({}) - def update(self, data=values.unset, ttl=values.unset): - """ - Update the SyncMapItemInstance + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match - :param dict data: The data - :param unicode ttl: The ttl + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: Updated SyncMapItemInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemInstance - """ - data = values.of({'Data': serialize.object(data), 'Ttl': ttl, }) + headers["Accept"] = "application/json" - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class SyncMapItemInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class SyncMapItemPage(Page): - class QueryResultOrder(object): - ASC = "asc" - DESC = "desc" + def get_instance(self, payload: Dict[str, Any]) -> SyncMapItemInstance: + """ + Build an instance of SyncMapItemInstance - class QueryFromBoundType(object): - INCLUSIVE = "inclusive" - EXCLUSIVE = "exclusive" + :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 __init__(self, version, payload, service_sid, map_sid, key=None): + def __repr__(self) -> str: """ - Initialize the SyncMapItemInstance + Provide a friendly representation - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemInstance + :returns: Machine friendly representation """ - super(SyncMapItemInstance, self).__init__(version) + return "" - # Marshaled Properties - self._properties = { - 'key': payload['key'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'map_sid': payload['map_sid'], - 'url': payload['url'], - 'revision': payload['revision'], - 'data': payload['data'], - 'date_expires': deserialize.iso8601_datetime(payload['date_expires']), - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'created_by': payload['created_by'], - } - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'map_sid': map_sid, - 'key': key or self._properties['key'], - } +class SyncMapItemList(ListResource): - @property - def _proxy(self): + def __init__(self, version: Version, service_sid: str, map_sid: str): """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Initialize the SyncMapItemList - :returns: SyncMapItemContext for this SyncMapItemInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemContext - """ - 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 + :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`. - @property - def key(self): """ - :returns: The key - :rtype: unicode - """ - return self._properties['key'] + super().__init__(version) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + # Path Solution + self._solution = { + "service_sid": service_sid, + "map_sid": map_sid, + } + self._uri = "/Services/{service_sid}/Maps/{map_sid}/Items".format( + **self._solution + ) - @property - def service_sid(self): - """ - :returns: The service_sid - :rtype: unicode - """ - return self._properties['service_sid'] + 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"}) - @property - def map_sid(self): - """ - :returns: The map_sid - :rtype: unicode - """ - return self._properties['map_sid'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] + headers["Accept"] = "application/json" - @property - def revision(self): - """ - :returns: The revision - :rtype: unicode - """ - return self._properties['revision'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def data(self): + 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]: """ - :returns: The data - :rtype: dict + 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 """ - return self._properties['data'] + limits = self._version.read_limits(limit, page_size) + page = self.page( + order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] + ) - @property - def date_expires(self): + 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]: """ - :returns: The date_expires - :rtype: datetime + 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 """ - return self._properties['date_expires'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] + ) - @property - def date_created(self): + 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]: """ - :returns: The date_created - :rtype: datetime + 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]: """ - return self._properties['date_created'] + 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. - @property - def date_updated(self): + :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: """ - :returns: The date_updated - :rtype: datetime + 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 """ - return self._properties['date_updated'] + data = values.of( + { + "Order": order, + "From": from_, + "Bounds": bounds, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def created_by(self): + headers = values.of({"Content-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 """ - :returns: The created_by - :rtype: unicode + 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: """ - return self._properties['created_by'] + 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 - def fetch(self): + :returns: Page of SyncMapItemInstance """ - Fetch a SyncMapItemInstance + response = self._version.domain.twilio.request("GET", target_url) + return SyncMapItemPage(self._version, response, self._solution) - :returns: Fetched SyncMapItemInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemInstance + async def get_page_async(self, target_url: str) -> SyncMapItemPage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of SyncMapItemInstance records from the API. + Request is executed immediately - def delete(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncMapItemInstance """ - Deletes the SyncMapItemInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncMapItemPage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def get(self, key: str) -> SyncMapItemContext: """ - return self._proxy.delete() + Constructs a SyncMapItemContext - def update(self, data=values.unset, ttl=values.unset): + :param key: The `key` value of the Sync Map Item resource to update. """ - Update the SyncMapItemInstance + return SyncMapItemContext( + self._version, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=key, + ) - :param dict data: The data - :param unicode ttl: The ttl + def __call__(self, key: str) -> SyncMapItemContext: + """ + Constructs a SyncMapItemContext - :returns: Updated SyncMapItemInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemInstance + :param key: The `key` value of the Sync Map Item resource to update. """ - return self._proxy.update(data=data, ttl=ttl, ) + return SyncMapItemContext( + self._version, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=key, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 index c8b3292e22..910560add0 100644 --- a/twilio/rest/sync/v1/service/sync_map/sync_map_permission.py +++ b/twilio/rest/sync/v1/service/sync_map/sync_map_permission.py @@ -1,453 +1,615 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import values +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 SyncMapPermissionList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +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 - def __init__(self, version, service_sid, map_sid): + @property + def _proxy(self) -> "SyncMapPermissionContext": """ - Initialize the SyncMapPermissionList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param service_sid: Sync Service Instance SID. - :param map_sid: Sync Map SID. + :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 - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionList - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionList + def delete(self) -> bool: """ - super(SyncMapPermissionList, self).__init__(version) + Deletes the SyncMapPermissionInstance - # 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=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the SyncMapPermissionInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the SyncMapPermissionInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance] + :returns: The fetched SyncMapPermissionInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_async(self) -> "SyncMapPermissionInstance": """ - Retrieve a single page of SyncMapPermissionInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the SyncMapPermissionInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of SyncMapPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionPage + :returns: The fetched SyncMapPermissionInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_async() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return SyncMapPermissionPage(self._version, response, self._solution) - - def get_page(self, target_url): + def update( + self, read: bool, write: bool, manage: bool + ) -> "SyncMapPermissionInstance": """ - Retrieve a specific page of SyncMapPermissionInstance records from the API. - Request is executed immediately + Update the SyncMapPermissionInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of SyncMapPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionPage + :returns: The updated SyncMapPermissionInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + read=read, + write=write, + manage=manage, ) - return SyncMapPermissionPage(self._version, response, self._solution) - - def get(self, identity): + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> "SyncMapPermissionInstance": """ - Constructs a SyncMapPermissionContext + Asynchronous coroutine to update the SyncMapPermissionInstance - :param identity: Identity of the user to whom the Sync Map Permission applies. + :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: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionContext - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionContext + :returns: The updated SyncMapPermissionInstance """ - return SyncMapPermissionContext( - self._version, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - identity=identity, + return await self._proxy.update_async( + read=read, + write=write, + manage=manage, ) - def __call__(self, identity): + def __repr__(self) -> str: """ - Constructs a SyncMapPermissionContext + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param identity: Identity of the user to whom the Sync Map Permission applies. - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionContext - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionContext +class SyncMapPermissionContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, map_sid: str, identity: str): """ - return SyncMapPermissionContext( - self._version, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - identity=identity, + 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 __repr__(self): + def delete(self) -> bool: """ - Provide a friendly representation + Deletes the SyncMapPermissionInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class SyncMapPermissionPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, response, solution): + async def delete_async(self) -> bool: """ - Initialize the SyncMapPermissionPage + Asynchronous coroutine that deletes the SyncMapPermissionInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Sync Service Instance SID. - :param map_sid: Sync Map SID. - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionPage - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionPage + :returns: True if delete succeeds, False otherwise """ - super(SyncMapPermissionPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def get_instance(self, payload): + def fetch(self) -> SyncMapPermissionInstance: """ - Build an instance of SyncMapPermissionInstance + Fetch the SyncMapPermissionInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.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'], + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], ) - def __repr__(self): + async def fetch_async(self) -> SyncMapPermissionInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the SyncMapPermissionInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched SyncMapPermissionInstance """ - return '' + headers = values.of({}) -class SyncMapPermissionContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Accept"] = "application/json" - def __init__(self, version, service_sid, map_sid, identity): - """ - Initialize the SyncMapPermissionContext + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param map_sid: Sync Map SID or unique name. - :param identity: Identity of the user to whom the Sync Map Permission applies. + return SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionContext - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionContext + def update( + self, read: bool, write: bool, manage: bool + ) -> SyncMapPermissionInstance: """ - super(SyncMapPermissionContext, self).__init__(version) + Update the SyncMapPermissionInstance - # 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) + :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`. - def fetch(self): + :returns: The updated SyncMapPermissionInstance """ - Fetch a SyncMapPermissionInstance - :returns: Fetched SyncMapPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance - """ - params = values.of({}) + 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" - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], ) - def delete(self): + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> SyncMapPermissionInstance: """ - Deletes the SyncMapPermissionInstance + Asynchronous coroutine to update the SyncMapPermissionInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :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`. - def update(self, read, write, manage): + :returns: The updated SyncMapPermissionInstance """ - Update the SyncMapPermissionInstance - :param bool read: Read access. - :param bool write: Write access. - :param bool manage: Manage access. + 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" - :returns: Updated SyncMapPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance - """ - data = values.of({'Read': read, 'Write': write, 'Manage': manage, }) + headers["Accept"] = "application/json" - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class SyncMapPermissionInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class SyncMapPermissionPage(Page): - def __init__(self, version, payload, service_sid, map_sid, identity=None): + def get_instance(self, payload: Dict[str, Any]) -> SyncMapPermissionInstance: """ - Initialize the SyncMapPermissionInstance + Build an instance of SyncMapPermissionInstance - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance + :param payload: Payload response from the API """ - super(SyncMapPermissionInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'map_sid': payload['map_sid'], - 'identity': payload['identity'], - 'read': payload['read'], - 'write': payload['write'], - 'manage': payload['manage'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'map_sid': map_sid, - 'identity': identity or self._properties['identity'], - } + return SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + ) - @property - def _proxy(self): + def __repr__(self) -> str: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Provide a friendly representation - :returns: SyncMapPermissionContext for this SyncMapPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionContext + :returns: Machine friendly representation """ - 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 + return "" - @property - def account_sid(self): - """ - :returns: Twilio Account SID. - :rtype: unicode + +class SyncMapPermissionList(ListResource): + + def __init__(self, version: Version, service_sid: str, map_sid: str): """ - return self._properties['account_sid'] + 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`. - @property - def service_sid(self): """ - :returns: Sync Service Instance SID. - :rtype: unicode + 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]: """ - return self._properties['service_sid'] + 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. - @property - def map_sid(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: Sync Map SID. - :rtype: unicode + 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]: """ - return self._properties['map_sid'] + 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. - @property - def identity(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: Identity of the user to whom the Sync Map Permission applies. - :rtype: unicode + 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]: """ - return self._properties['identity'] + Lists SyncMapPermissionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def read(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: Read access. - :rtype: bool + 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]: """ - return self._properties['read'] + 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. - @property - def write(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: Write access. - :rtype: bool + 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: """ - return self._properties['write'] + Retrieve a single page of SyncMapPermissionInstance records from the API. + Request is executed immediately - @property - def manage(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: Manage access. - :rtype: bool + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['manage'] + Asynchronously retrieve a single page of SyncMapPermissionInstance records from the API. + Request is executed immediately - @property - def url(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: URL of this Sync Map Permission. - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of SyncMapPermissionInstance """ - Fetch a SyncMapPermissionInstance + response = self._version.domain.twilio.request("GET", target_url) + return SyncMapPermissionPage(self._version, response, self._solution) - :returns: Fetched SyncMapPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance + async def get_page_async(self, target_url: str) -> SyncMapPermissionPage: """ - return self._proxy.fetch() + 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 - def delete(self): + :returns: Page of SyncMapPermissionInstance """ - Deletes the SyncMapPermissionInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncMapPermissionPage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def get(self, identity: str) -> SyncMapPermissionContext: """ - return self._proxy.delete() + Constructs a SyncMapPermissionContext - def update(self, read, write, manage): + :param identity: The application-defined string that uniquely identifies the User's Sync Map Permission resource to update. """ - Update the SyncMapPermissionInstance + return SyncMapPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=identity, + ) - :param bool read: Read access. - :param bool write: Write access. - :param bool manage: Manage access. + def __call__(self, identity: str) -> SyncMapPermissionContext: + """ + Constructs a SyncMapPermissionContext - :returns: Updated SyncMapPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance + :param identity: The application-defined string that uniquely identifies the User's Sync Map Permission resource to update. """ - return self._proxy.update(read, write, manage, ) + return SyncMapPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=identity, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/sync/v1/service/sync_stream/__init__.py b/twilio/rest/sync/v1/service/sync_stream/__init__.py index 9027b4c7ad..a7f4128e05 100644 --- a/twilio/rest/sync/v1/service/sync_stream/__init__.py +++ b/twilio/rest/sync/v1/service/sync_stream/__init__.py @@ -1,493 +1,671 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 SyncStreamList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, service_sid): - """ - Initialize the SyncStreamList +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") - :param Version version: Version that contains the resource - :param service_sid: Service Instance SID. + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[SyncStreamContext] = None - :returns: twilio.rest.sync.v1.service.sync_stream.SyncStreamList - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamList + @property + def _proxy(self) -> "SyncStreamContext": """ - super(SyncStreamList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Streams'.format(**self._solution) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def create(self, unique_name=values.unset, ttl=values.unset): + :returns: SyncStreamContext for this SyncStreamInstance """ - Create a new SyncStreamInstance - - :param unicode unique_name: Stream unique name. - :param unicode ttl: Stream TTL. + if self._context is None: + self._context = SyncStreamContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: Newly created SyncStreamInstance - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamInstance + def delete(self) -> bool: """ - data = values.of({'UniqueName': unique_name, 'Ttl': ttl, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + Deletes the SyncStreamInstance - return SyncStreamInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.sync_stream.SyncStreamInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the SyncStreamInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the SyncStreamInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.sync_stream.SyncStreamInstance] + :returns: The fetched SyncStreamInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_async(self) -> "SyncStreamInstance": """ - Retrieve a single page of SyncStreamInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the SyncStreamInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of SyncStreamInstance - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamPage + :returns: The fetched SyncStreamInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + return await self._proxy.fetch_async() - return SyncStreamPage(self._version, response, self._solution) - - def get_page(self, target_url): + def update(self, ttl: Union[int, object] = values.unset) -> "SyncStreamInstance": """ - Retrieve a specific page of SyncStreamInstance records from the API. - Request is executed immediately + Update the SyncStreamInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of SyncStreamInstance - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamPage + :returns: The updated SyncStreamInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + ttl=ttl, ) - return SyncStreamPage(self._version, response, self._solution) - - def get(self, sid): + async def update_async( + self, ttl: Union[int, object] = values.unset + ) -> "SyncStreamInstance": """ - Constructs a SyncStreamContext + Asynchronous coroutine to update the SyncStreamInstance - :param sid: Stream SID or unique name. + :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: twilio.rest.sync.v1.service.sync_stream.SyncStreamContext - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamContext + :returns: The updated SyncStreamInstance """ - return SyncStreamContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_async( + ttl=ttl, + ) - def __call__(self, sid): + @property + def stream_messages(self) -> StreamMessageList: """ - Constructs a SyncStreamContext - - :param sid: Stream SID or unique name. - - :returns: twilio.rest.sync.v1.service.sync_stream.SyncStreamContext - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamContext + Access the stream_messages """ - return SyncStreamContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.stream_messages - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class SyncStreamPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class SyncStreamContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the SyncStreamPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Service Instance SID. + Initialize the SyncStreamContext - :returns: twilio.rest.sync.v1.service.sync_stream.SyncStreamPage - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamPage + :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(SyncStreamPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Streams/{sid}".format(**self._solution) - def get_instance(self, payload): + self._stream_messages: Optional[StreamMessageList] = None + + def delete(self) -> bool: """ - Build an instance of SyncStreamInstance + Deletes the SyncStreamInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.sync.v1.service.sync_stream.SyncStreamInstance - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamInstance + :returns: True if delete succeeds, False otherwise """ - return SyncStreamInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the SyncStreamInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class SyncStreamContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, service_sid, sid): + def fetch(self) -> SyncStreamInstance: """ - Initialize the SyncStreamContext + Fetch the SyncStreamInstance - :param Version version: Version that contains the resource - :param service_sid: The service_sid - :param sid: Stream SID or unique name. - :returns: twilio.rest.sync.v1.service.sync_stream.SyncStreamContext - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamContext + :returns: The fetched SyncStreamInstance """ - super(SyncStreamContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Streams/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._stream_messages = None + headers["Accept"] = "application/json" - def fetch(self): + 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: """ - Fetch a SyncStreamInstance + Asynchronous coroutine to fetch the SyncStreamInstance - :returns: Fetched SyncStreamInstance - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamInstance + + :returns: The fetched SyncStreamInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + def update(self, ttl: Union[int, object] = values.unset) -> SyncStreamInstance: """ - Deletes the SyncStreamInstance + Update the SyncStreamInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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._version.delete('delete', self._uri) - def update(self, ttl=values.unset): + 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: """ - Update the SyncStreamInstance + Asynchronous coroutine to update the SyncStreamInstance - :param unicode ttl: Stream TTL. + :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: Updated SyncStreamInstance - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamInstance + :returns: The updated SyncStreamInstance """ - data = values.of({'Ttl': ttl, }) - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) @property - def stream_messages(self): + def stream_messages(self) -> StreamMessageList: """ Access the stream_messages - - :returns: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessageList - :rtype: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessageList """ if self._stream_messages is None: self._stream_messages = StreamMessageList( self._version, - service_sid=self._solution['service_sid'], - stream_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) return self._stream_messages - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class SyncStreamInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the SyncStreamInstance - - :returns: twilio.rest.sync.v1.service.sync_stream.SyncStreamInstance - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamInstance - """ - super(SyncStreamInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'unique_name': payload['unique_name'], - 'account_sid': payload['account_sid'], - 'service_sid': payload['service_sid'], - 'url': payload['url'], - 'links': payload['links'], - 'date_expires': deserialize.iso8601_datetime(payload['date_expires']), - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'created_by': payload['created_by'], - } - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } +class SyncStreamPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> SyncStreamInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of SyncStreamInstance - :returns: SyncStreamContext for this SyncStreamInstance - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = SyncStreamContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + return SyncStreamInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def sid(self): + def __repr__(self) -> str: """ - :returns: Stream SID. - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def unique_name(self): + :returns: Machine friendly representation """ - :returns: Stream unique name. - :rtype: unicode + return "" + + +class SyncStreamList(ListResource): + + def __init__(self, version: Version, service_sid: str): """ - return self._properties['unique_name'] + 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. - @property - def account_sid(self): """ - :returns: Twilio Account SID. - :rtype: unicode + 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: """ - return self._properties['account_sid'] + Create the SyncStreamInstance - @property - def service_sid(self): + :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 """ - :returns: Service Instance SID. - :rtype: unicode + + 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: """ - return self._properties['service_sid'] + Asynchronously create the SyncStreamInstance - @property - def url(self): + :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 """ - :returns: URL of this Stream. - :rtype: unicode + + 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]: """ - return self._properties['url'] + 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. - @property - def links(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: Nested resource URLs. - :rtype: unicode + 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]: """ - return self._properties['links'] + 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. - @property - def date_expires(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The date this Stream expires. - :rtype: datetime + 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]: """ - return self._properties['date_expires'] + Lists SyncStreamInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def date_created(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The date this Stream was created. - :rtype: datetime + 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]: """ - return self._properties['date_created'] + 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. - @property - def date_updated(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The date this Stream was updated. - :rtype: datetime + 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: """ - return self._properties['date_updated'] + Retrieve a single page of SyncStreamInstance records from the API. + Request is executed immediately - @property - def created_by(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: Identity of the Stream creator. - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['created_by'] + Asynchronously retrieve a single page of SyncStreamInstance records from the API. + Request is executed immediately - def fetch(self): + :param page_token: PageToken provided by the API + :param page_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 """ - Fetch a 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) - :returns: Fetched SyncStreamInstance - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamInstance + def get_page(self, target_url: str) -> SyncStreamPage: """ - return self._proxy.fetch() + 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 - def delete(self): + :returns: Page of SyncStreamInstance """ - Deletes the SyncStreamInstance + response = self._version.domain.twilio.request("GET", target_url) + return SyncStreamPage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def get_page_async(self, target_url: str) -> SyncStreamPage: """ - return self._proxy.delete() + 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 - def update(self, ttl=values.unset): + :returns: Page of SyncStreamInstance """ - Update the SyncStreamInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncStreamPage(self._version, response, self._solution) - :param unicode ttl: Stream TTL. + def get(self, sid: str) -> SyncStreamContext: + """ + Constructs a SyncStreamContext - :returns: Updated SyncStreamInstance - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamInstance + :param sid: The SID of the Stream resource to update. """ - return self._proxy.update(ttl=ttl, ) + return SyncStreamContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - @property - def stream_messages(self): + def __call__(self, sid: str) -> SyncStreamContext: """ - Access the stream_messages + Constructs a SyncStreamContext - :returns: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessageList - :rtype: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessageList + :param sid: The SID of the Stream resource to update. """ - return self._proxy.stream_messages + return SyncStreamContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/sync/v1/service/sync_stream/stream_message.py b/twilio/rest/sync/v1/service/sync_stream/stream_message.py index 5d4ead97b8..bcce239975 100644 --- a/twilio/rest/sync/v1/service/sync_stream/stream_message.py +++ b/twilio/rest/sync/v1/service/sync_stream/stream_message.py @@ -1,161 +1,146 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import serialize -from twilio.base import values +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.page import Page +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 "".format(context) class StreamMessageList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - def __init__(self, version, service_sid, stream_sid): + def __init__(self, version: Version, service_sid: str, stream_sid: str): """ Initialize the StreamMessageList - :param Version version: Version that contains the resource - :param service_sid: Service Instance SID. - :param stream_sid: Stream SID. + :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. - :returns: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessageList - :rtype: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessageList """ - super(StreamMessageList, self).__init__(version) + 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) + 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): + def create(self, data: object) -> StreamMessageInstance: """ - Create a new StreamMessageInstance + Create the StreamMessageInstance - :param dict data: Stream Message body. + :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: Newly created StreamMessageInstance - :rtype: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessageInstance + :returns: The created StreamMessageInstance """ - data = values.of({'Data': serialize.object(data), }) + + 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( - 'POST', - self._uri, - data=data, + 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'], + service_sid=self._solution["service_sid"], + stream_sid=self._solution["stream_sid"], ) - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str + async def create_async(self, data: object) -> StreamMessageInstance: """ - return '' - + Asynchronously create the StreamMessageInstance -class StreamMessagePage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :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. - def __init__(self, version, response, solution): + :returns: The created StreamMessageInstance """ - Initialize the StreamMessagePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Service Instance SID. - :param stream_sid: Stream SID. - :returns: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessagePage - :rtype: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessagePage - """ - super(StreamMessagePage, self).__init__(version, response) + data = values.of( + { + "Data": serialize.object(data), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - # Path Solution - self._solution = solution + headers["Content-Type"] = "application/x-www-form-urlencoded" - def get_instance(self, payload): - """ - Build an instance of StreamMessageInstance + headers["Accept"] = "application/json" - :param dict payload: Payload response from the API + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessageInstance - :rtype: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessageInstance - """ return StreamMessageInstance( self._version, payload, - service_sid=self._solution['service_sid'], - stream_sid=self._solution['stream_sid'], + service_sid=self._solution["service_sid"], + stream_sid=self._solution["stream_sid"], ) - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class StreamMessageInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, payload, service_sid, stream_sid): - """ - Initialize the StreamMessageInstance - - :returns: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessageInstance - :rtype: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessageInstance - """ - super(StreamMessageInstance, self).__init__(version) - - # Marshaled Properties - self._properties = {'sid': payload['sid'], 'data': payload['data'], } - - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'stream_sid': stream_sid, } - - @property - def sid(self): - """ - :returns: Stream Message SID. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def data(self): - """ - :returns: Stream Message body. - :rtype: dict - """ - return self._properties['data'] - - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" 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 "" diff --git a/twilio/rest/taskrouter/__init__.py b/twilio/rest/taskrouter/__init__.py index fd026a588c..73d3ee8250 100644 --- a/twilio/rest/taskrouter/__init__.py +++ b/twilio/rest/taskrouter/__init__.py @@ -1,53 +1,15 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" +from warnings import warn -from twilio.base.domain import Domain -from twilio.rest.taskrouter.v1 import V1 +from twilio.rest.taskrouter.TaskrouterBase import TaskrouterBase +from twilio.rest.taskrouter.v1.workspace import WorkspaceList -class Taskrouter(Domain): - - def __init__(self, twilio): - """ - Initialize the Taskrouter Domain - - :returns: Domain for Taskrouter - :rtype: twilio.rest.taskrouter.Taskrouter - """ - super(Taskrouter, self).__init__(twilio) - - self.base_url = 'https://taskrouter.twilio.com' - - # Versions - self._v1 = None - +class Taskrouter(TaskrouterBase): @property - def v1(self): - """ - :returns: Version v1 of taskrouter - :rtype: twilio.rest.taskrouter.v1.V1 - """ - if self._v1 is None: - self._v1 = V1(self) - return self._v1 - - @property - def workspaces(self): - """ - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceList - """ + def workspaces(self) -> WorkspaceList: + warn( + "workspaces is deprecated. Use v1.workspaces instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v1.workspaces - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/taskrouter/v1/__init__.py b/twilio/rest/taskrouter/v1/__init__.py index c1ea2e7744..a17eeccc2a 100644 --- a/twilio/rest/taskrouter/v1/__init__.py +++ b/twilio/rest/taskrouter/v1/__init__.py @@ -1,42 +1,43 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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): + def __init__(self, domain: Domain): """ Initialize the V1 version of Taskrouter - :returns: V1 version of Taskrouter - :rtype: twilio.rest.taskrouter.v1.V1.V1 + :param domain: The Twilio.taskrouter domain """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._workspaces = None + super().__init__(domain, "v1") + self._workspaces: Optional[WorkspaceList] = None @property - def workspaces(self): - """ - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceList - """ + def workspaces(self) -> WorkspaceList: if self._workspaces is None: self._workspaces = WorkspaceList(self) return self._workspaces - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/taskrouter/v1/workspace/__init__.py b/twilio/rest/taskrouter/v1/workspace/__init__.py index 81a63794c0..086e3e1747 100644 --- a/twilio/rest/taskrouter/v1/workspace/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/__init__.py @@ -1,16 +1,24 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 @@ -19,778 +27,953 @@ 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 - +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 WorkspaceList(ListResource): - """ """ - def __init__(self, version): - """ - Initialize the WorkspaceList +class WorkspaceInstance(InstanceResource): - :param Version version: Version that contains the resource + class QueueOrder(object): + FIFO = "FIFO" + LIFO = "LIFO" - :returns: twilio.rest.taskrouter.v1.workspace.WorkspaceList - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceList - """ - super(WorkspaceList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {} - self._uri = '/Workspaces'.format(**self._solution) + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[WorkspaceContext] = None - def stream(self, friendly_name=values.unset, limit=None, page_size=None): + @property + def _proxy(self) -> "WorkspaceContext": """ - 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. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param unicode friendly_name: The friendly_name - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :returns: WorkspaceContext for this WorkspaceInstance + """ + if self._context is None: + self._context = WorkspaceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.WorkspaceInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the WorkspaceInstance - page = self.page(friendly_name=friendly_name, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, friendly_name=values.unset, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists WorkspaceInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the WorkspaceInstance - :param unicode friendly_name: The friendly_name - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.WorkspaceInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(friendly_name=friendly_name, limit=limit, page_size=page_size, )) + return await self._proxy.delete_async() - def page(self, friendly_name=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch(self) -> "WorkspaceInstance": """ - Retrieve a single page of WorkspaceInstance records from the API. - Request is executed immediately + Fetch the WorkspaceInstance - :param unicode friendly_name: The friendly_name - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of WorkspaceInstance - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspacePage + :returns: The fetched WorkspaceInstance """ - params = values.of({ - 'FriendlyName': friendly_name, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + async def fetch_async(self) -> "WorkspaceInstance": + """ + Asynchronous coroutine to fetch the WorkspaceInstance - return WorkspacePage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched WorkspaceInstance """ - Retrieve a specific page of WorkspaceInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_async() - :param str target_url: API-generated URL for the requested results page + 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 - :returns: Page of WorkspaceInstance - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspacePage + :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 """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, ) - return WorkspacePage(self._version, response, self._solution) + 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, + ) - def create(self, friendly_name, event_callback_url=values.unset, - events_filter=values.unset, multi_task_enabled=values.unset, - template=values.unset, prioritize_queue_order=values.unset): + @property + def activities(self) -> ActivityList: """ - Create a new WorkspaceInstance - - :param unicode friendly_name: The friendly_name - :param unicode event_callback_url: The event_callback_url - :param unicode events_filter: The events_filter - :param bool multi_task_enabled: The multi_task_enabled - :param unicode template: The template - :param WorkspaceInstance.QueueOrder prioritize_queue_order: The prioritize_queue_order + Access the activities + """ + return self._proxy.activities - :returns: Newly created WorkspaceInstance - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceInstance + @property + def events(self) -> EventList: + """ + Access the events """ - data = values.of({ - 'FriendlyName': friendly_name, - 'EventCallbackUrl': event_callback_url, - 'EventsFilter': events_filter, - 'MultiTaskEnabled': multi_task_enabled, - 'Template': template, - 'PrioritizeQueueOrder': prioritize_queue_order, - }) + return self._proxy.events - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + @property + def tasks(self) -> TaskList: + """ + Access the tasks + """ + return self._proxy.tasks - return WorkspaceInstance(self._version, payload, ) + @property + def task_channels(self) -> TaskChannelList: + """ + Access the task_channels + """ + return self._proxy.task_channels - def get(self, sid): + @property + def task_queues(self) -> TaskQueueList: """ - Constructs a WorkspaceContext + Access the task_queues + """ + return self._proxy.task_queues - :param sid: The sid + @property + def workers(self) -> WorkerList: + """ + Access the workers + """ + return self._proxy.workers - :returns: twilio.rest.taskrouter.v1.workspace.WorkspaceContext - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceContext + @property + def workflows(self) -> WorkflowList: + """ + Access the workflows """ - return WorkspaceContext(self._version, sid=sid, ) + return self._proxy.workflows - def __call__(self, sid): + @property + def cumulative_statistics(self) -> WorkspaceCumulativeStatisticsList: """ - Constructs a WorkspaceContext + Access the cumulative_statistics + """ + return self._proxy.cumulative_statistics - :param sid: The sid + @property + def real_time_statistics(self) -> WorkspaceRealTimeStatisticsList: + """ + Access the real_time_statistics + """ + return self._proxy.real_time_statistics - :returns: twilio.rest.taskrouter.v1.workspace.WorkspaceContext - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceContext + @property + def statistics(self) -> WorkspaceStatisticsList: + """ + Access the statistics """ - return WorkspaceContext(self._version, sid=sid, ) + return self._proxy.statistics - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class WorkspacePage(Page): - """ """ +class WorkspaceContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the WorkspacePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the WorkspaceContext - :returns: twilio.rest.taskrouter.v1.workspace.WorkspacePage - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspacePage + :param version: Version that contains the resource + :param sid: The SID of the Workspace resource to update. """ - super(WorkspacePage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/Workspaces/{sid}".format(**self._solution) - def get_instance(self, payload): + 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: """ - Build an instance of WorkspaceInstance + Deletes the WorkspaceInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.taskrouter.v1.workspace.WorkspaceInstance - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceInstance + :returns: True if delete succeeds, False otherwise """ - return WorkspaceInstance(self._version, payload, ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the WorkspaceInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class WorkspaceContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, sid): + def fetch(self) -> WorkspaceInstance: """ - Initialize the WorkspaceContext + Fetch the WorkspaceInstance - :param Version version: Version that contains the resource - :param sid: The sid - :returns: twilio.rest.taskrouter.v1.workspace.WorkspaceContext - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceContext + :returns: The fetched WorkspaceInstance """ - super(WorkspaceContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Workspaces/{sid}'.format(**self._solution) - - # Dependents - self._activities = None - self._events = None - self._tasks = None - self._task_queues = None - self._workers = None - self._workflows = None - self._statistics = None - self._real_time_statistics = None - self._cumulative_statistics = None - self._task_channels = None - - def fetch(self): - """ - Fetch a WorkspaceInstance - - :returns: Fetched WorkspaceInstance - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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"], ) - return WorkspaceInstance(self._version, payload, sid=self._solution['sid'], ) + async def fetch_async(self) -> WorkspaceInstance: + """ + Asynchronous coroutine to fetch the WorkspaceInstance - def update(self, default_activity_sid=values.unset, - event_callback_url=values.unset, events_filter=values.unset, - friendly_name=values.unset, multi_task_enabled=values.unset, - timeout_activity_sid=values.unset, - prioritize_queue_order=values.unset): + + :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 unicode default_activity_sid: The default_activity_sid - :param unicode event_callback_url: The event_callback_url - :param unicode events_filter: The events_filter - :param unicode friendly_name: The friendly_name - :param bool multi_task_enabled: The multi_task_enabled - :param unicode timeout_activity_sid: The timeout_activity_sid - :param WorkspaceInstance.QueueOrder prioritize_queue_order: The prioritize_queue_order - - :returns: Updated WorkspaceInstance - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceInstance - """ - data = values.of({ - 'DefaultActivitySid': default_activity_sid, - 'EventCallbackUrl': event_callback_url, - 'EventsFilter': events_filter, - 'FriendlyName': friendly_name, - 'MultiTaskEnabled': multi_task_enabled, - 'TimeoutActivitySid': timeout_activity_sid, - 'PrioritizeQueueOrder': prioritize_queue_order, - }) + :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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) - return WorkspaceInstance(self._version, payload, sid=self._solution['sid'], ) + 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({}) - def delete(self): - """ - Deletes the WorkspaceInstance + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + 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): + def activities(self) -> ActivityList: """ Access the activities - - :returns: twilio.rest.taskrouter.v1.workspace.activity.ActivityList - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityList """ if self._activities is None: - self._activities = ActivityList(self._version, workspace_sid=self._solution['sid'], ) + self._activities = ActivityList( + self._version, + self._solution["sid"], + ) return self._activities @property - def events(self): + def events(self) -> EventList: """ Access the events - - :returns: twilio.rest.taskrouter.v1.workspace.event.EventList - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventList """ if self._events is None: - self._events = EventList(self._version, workspace_sid=self._solution['sid'], ) + self._events = EventList( + self._version, + self._solution["sid"], + ) return self._events @property - def tasks(self): + def tasks(self) -> TaskList: """ Access the tasks - - :returns: twilio.rest.taskrouter.v1.workspace.task.TaskList - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskList """ if self._tasks is None: - self._tasks = TaskList(self._version, workspace_sid=self._solution['sid'], ) + self._tasks = TaskList( + self._version, + self._solution["sid"], + ) return self._tasks @property - def task_queues(self): + def task_channels(self) -> TaskChannelList: """ - Access the task_queues + Access the task_channels + """ + if self._task_channels is None: + self._task_channels = TaskChannelList( + self._version, + self._solution["sid"], + ) + return self._task_channels - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueList - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueList + @property + def task_queues(self) -> TaskQueueList: + """ + Access the task_queues """ if self._task_queues is None: - self._task_queues = TaskQueueList(self._version, workspace_sid=self._solution['sid'], ) + self._task_queues = TaskQueueList( + self._version, + self._solution["sid"], + ) return self._task_queues @property - def workers(self): + def workers(self) -> WorkerList: """ Access the workers - - :returns: twilio.rest.taskrouter.v1.workspace.worker.WorkerList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerList """ if self._workers is None: - self._workers = WorkerList(self._version, workspace_sid=self._solution['sid'], ) + self._workers = WorkerList( + self._version, + self._solution["sid"], + ) return self._workers @property - def workflows(self): + def workflows(self) -> WorkflowList: """ Access the workflows - - :returns: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowList - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowList """ if self._workflows is None: - self._workflows = WorkflowList(self._version, workspace_sid=self._solution['sid'], ) + self._workflows = WorkflowList( + self._version, + self._solution["sid"], + ) return self._workflows @property - def statistics(self): + def cumulative_statistics(self) -> WorkspaceCumulativeStatisticsList: """ - Access the statistics - - :returns: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsList + Access the cumulative_statistics """ - if self._statistics is None: - self._statistics = WorkspaceStatisticsList(self._version, workspace_sid=self._solution['sid'], ) - return self._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): + def real_time_statistics(self) -> WorkspaceRealTimeStatisticsList: """ Access the real_time_statistics - - :returns: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsList """ if self._real_time_statistics is None: self._real_time_statistics = WorkspaceRealTimeStatisticsList( self._version, - workspace_sid=self._solution['sid'], + self._solution["sid"], ) return self._real_time_statistics @property - def cumulative_statistics(self): + def statistics(self) -> WorkspaceStatisticsList: """ - Access the cumulative_statistics - - :returns: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsList + Access the statistics """ - if self._cumulative_statistics is None: - self._cumulative_statistics = WorkspaceCumulativeStatisticsList( + if self._statistics is None: + self._statistics = WorkspaceStatisticsList( self._version, - workspace_sid=self._solution['sid'], + self._solution["sid"], ) - return self._cumulative_statistics + return self._statistics - @property - def task_channels(self): + def __repr__(self) -> str: """ - Access the task_channels + Provide a friendly representation - :returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelList - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelList + :returns: Machine friendly representation """ - if self._task_channels is None: - self._task_channels = TaskChannelList(self._version, workspace_sid=self._solution['sid'], ) - return self._task_channels + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - def __repr__(self): + +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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - + return "" -class WorkspaceInstance(InstanceResource): - """ """ - class QueueOrder(object): - FIFO = "FIFO" - LIFO = "LIFO" +class WorkspaceList(ListResource): - def __init__(self, version, payload, sid=None): - """ - Initialize the WorkspaceInstance - - :returns: twilio.rest.taskrouter.v1.workspace.WorkspaceInstance - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceInstance - """ - super(WorkspaceInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'default_activity_name': payload['default_activity_name'], - 'default_activity_sid': payload['default_activity_sid'], - 'event_callback_url': payload['event_callback_url'], - 'events_filter': payload['events_filter'], - 'friendly_name': payload['friendly_name'], - 'multi_task_enabled': payload['multi_task_enabled'], - 'sid': payload['sid'], - 'timeout_activity_name': payload['timeout_activity_name'], - 'timeout_activity_sid': payload['timeout_activity_sid'], - 'prioritize_queue_order': payload['prioritize_queue_order'], - 'url': payload['url'], - 'links': payload['links'], - } + def __init__(self, version: Version): + """ + Initialize the WorkspaceList - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + :param version: Version that contains the resource - @property - def _proxy(self): """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + super().__init__(version) - :returns: WorkspaceContext for this WorkspaceInstance - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceContext - """ - if self._context is None: - self._context = WorkspaceContext(self._version, sid=self._solution['sid'], ) - return self._context + self._uri = "/Workspaces" - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + 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: """ - return self._properties['account_sid'] + Create the WorkspaceInstance - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + :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: - @property - def date_updated(self): + :returns: The created WorkspaceInstance """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] - @property - def default_activity_name(self): - """ - :returns: The default_activity_name - :rtype: unicode - """ - return self._properties['default_activity_name'] + 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"}) - @property - def default_activity_sid(self): - """ - :returns: The default_activity_sid - :rtype: unicode - """ - return self._properties['default_activity_sid'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def event_callback_url(self): - """ - :returns: The event_callback_url - :rtype: unicode - """ - return self._properties['event_callback_url'] + headers["Accept"] = "application/json" - @property - def events_filter(self): - """ - :returns: The events_filter - :rtype: unicode - """ - return self._properties['events_filter'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] + 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"}) - @property - def multi_task_enabled(self): - """ - :returns: The multi_task_enabled - :rtype: bool - """ - return self._properties['multi_task_enabled'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + headers["Accept"] = "application/json" - @property - def timeout_activity_name(self): - """ - :returns: The timeout_activity_name - :rtype: unicode - """ - return self._properties['timeout_activity_name'] + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def timeout_activity_sid(self): - """ - :returns: The timeout_activity_sid - :rtype: unicode - """ - return self._properties['timeout_activity_sid'] + return WorkspaceInstance(self._version, payload) - @property - def prioritize_queue_order(self): - """ - :returns: The prioritize_queue_order - :rtype: WorkspaceInstance.QueueOrder + def stream( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WorkspaceInstance]: """ - return self._properties['prioritize_queue_order'] + 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. - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] + :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) - @property - def links(self): - """ - :returns: The links - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['links'] + limits = self._version.read_limits(limit, page_size) + page = self.page(friendly_name=friendly_name, page_size=limits["page_size"]) - def fetch(self): - """ - Fetch a WorkspaceInstance + return self._version.stream(page, limits["limit"]) - :returns: Fetched WorkspaceInstance - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceInstance + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WorkspaceInstance]: """ - return self._proxy.fetch() + 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) - def update(self, default_activity_sid=values.unset, - event_callback_url=values.unset, events_filter=values.unset, - friendly_name=values.unset, multi_task_enabled=values.unset, - timeout_activity_sid=values.unset, - prioritize_queue_order=values.unset): + :returns: Generator that will yield up to limit results """ - Update the WorkspaceInstance + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) - :param unicode default_activity_sid: The default_activity_sid - :param unicode event_callback_url: The event_callback_url - :param unicode events_filter: The events_filter - :param unicode friendly_name: The friendly_name - :param bool multi_task_enabled: The multi_task_enabled - :param unicode timeout_activity_sid: The timeout_activity_sid - :param WorkspaceInstance.QueueOrder prioritize_queue_order: The prioritize_queue_order + return self._version.stream_async(page, limits["limit"]) - :returns: Updated WorkspaceInstance - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceInstance + def list( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[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, + 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, + ) ) - def delete(self): + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WorkspaceInstance]: """ - Deletes the 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. - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() + :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, + ) + ] - @property - def activities(self): + 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: """ - Access the activities + Retrieve a single page of WorkspaceInstance records from the API. + Request is executed immediately - :returns: twilio.rest.taskrouter.v1.workspace.activity.ActivityList - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityList - """ - return self._proxy.activities + :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 - @property - def events(self): + :returns: Page of WorkspaceInstance """ - Access the events + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: twilio.rest.taskrouter.v1.workspace.event.EventList - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventList - """ - return self._proxy.events + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def tasks(self): - """ - Access the tasks + headers["Accept"] = "application/json" - :returns: twilio.rest.taskrouter.v1.workspace.task.TaskList - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskList - """ - return self._proxy.tasks + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WorkspacePage(self._version, response) - @property - def task_queues(self): + 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: """ - Access the task_queues + Asynchronously retrieve a single page of WorkspaceInstance records from the API. + Request is executed immediately - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueList - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueList - """ - return self._proxy.task_queues + :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 - @property - def workers(self): + :returns: Page of WorkspaceInstance """ - Access the workers + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: twilio.rest.taskrouter.v1.workspace.worker.WorkerList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerList - """ - return self._proxy.workers + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def workflows(self): - """ - Access the workflows + headers["Accept"] = "application/json" - :returns: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowList - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowList - """ - return self._proxy.workflows + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WorkspacePage(self._version, response) - @property - def statistics(self): + def get_page(self, target_url: str) -> WorkspacePage: """ - Access the statistics + Retrieve a specific page of WorkspaceInstance records from the API. + Request is executed immediately - :returns: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsList + :param target_url: API-generated URL for the requested results page + + :returns: Page of WorkspaceInstance """ - return self._proxy.statistics + response = self._version.domain.twilio.request("GET", target_url) + return WorkspacePage(self._version, response) - @property - def real_time_statistics(self): + async def get_page_async(self, target_url: str) -> WorkspacePage: """ - Access the real_time_statistics + Asynchronously retrieve a specific page of WorkspaceInstance records from the API. + Request is executed immediately - :returns: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsList + :param target_url: API-generated URL for the requested results page + + :returns: Page of WorkspaceInstance """ - return self._proxy.real_time_statistics + response = await self._version.domain.twilio.request_async("GET", target_url) + return WorkspacePage(self._version, response) - @property - def cumulative_statistics(self): + def get(self, sid: str) -> WorkspaceContext: """ - Access the cumulative_statistics + Constructs a WorkspaceContext - :returns: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsList + :param sid: The SID of the Workspace resource to update. """ - return self._proxy.cumulative_statistics + return WorkspaceContext(self._version, sid=sid) - @property - def task_channels(self): + def __call__(self, sid: str) -> WorkspaceContext: """ - Access the task_channels + Constructs a WorkspaceContext - :returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelList - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelList + :param sid: The SID of the Workspace resource to update. """ - return self._proxy.task_channels + return WorkspaceContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/taskrouter/v1/workspace/activity.py b/twilio/rest/taskrouter/v1/workspace/activity.py index affb6eb311..4e3e416af7 100644 --- a/twilio/rest/taskrouter/v1/workspace/activity.py +++ b/twilio/rest/taskrouter/v1/workspace/activity.py @@ -1,461 +1,686 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 ActivityList(ListResource): - """ """ +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 - def __init__(self, version, workspace_sid): + @property + def _proxy(self) -> "ActivityContext": """ - Initialize the ActivityList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid + :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 - :returns: twilio.rest.taskrouter.v1.workspace.activity.ActivityList - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityList + def delete(self) -> bool: """ - super(ActivityList, self).__init__(version) + Deletes the ActivityInstance - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } - self._uri = '/Workspaces/{workspace_sid}/Activities'.format(**self._solution) - def stream(self, friendly_name=values.unset, available=values.unset, limit=None, - page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 unicode friendly_name: The friendly_name - :param unicode available: The available - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the ActivityInstance - page = self.page(friendly_name=friendly_name, available=available, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, friendly_name=values.unset, available=values.unset, limit=None, - page_size=None): + def fetch(self) -> "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. + Fetch the ActivityInstance - :param unicode friendly_name: The friendly_name - :param unicode available: The available - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance] + :returns: The fetched ActivityInstance """ - return list(self.stream( - friendly_name=friendly_name, - available=available, - limit=limit, - page_size=page_size, - )) + return self._proxy.fetch() - def page(self, friendly_name=values.unset, available=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_async(self) -> "ActivityInstance": """ - Retrieve a single page of ActivityInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the ActivityInstance - :param unicode friendly_name: The friendly_name - :param unicode available: The available - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of ActivityInstance - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityPage + :returns: The fetched ActivityInstance """ - params = values.of({ - 'FriendlyName': friendly_name, - 'Available': available, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return await self._proxy.fetch_async() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return ActivityPage(self._version, response, self._solution) - - def get_page(self, target_url): + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> "ActivityInstance": """ - Retrieve a specific page of ActivityInstance records from the API. - Request is executed immediately + Update the ActivityInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of ActivityInstance - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityPage + :returns: The updated ActivityInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + friendly_name=friendly_name, ) - return ActivityPage(self._version, response, self._solution) - - def create(self, friendly_name, available=values.unset): + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "ActivityInstance": """ - Create a new ActivityInstance + Asynchronous coroutine to update the ActivityInstance - :param unicode friendly_name: The friendly_name - :param bool available: The available + :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: Newly created ActivityInstance - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance + :returns: The updated ActivityInstance """ - data = values.of({'FriendlyName': friendly_name, 'Available': available, }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, + return await self._proxy.update_async( + friendly_name=friendly_name, ) - return ActivityInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a ActivityContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param sid: The sid - :returns: twilio.rest.taskrouter.v1.workspace.activity.ActivityContext - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityContext +class ActivityContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, sid: str): """ - return ActivityContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + Initialize the ActivityContext - def __call__(self, sid): + :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. """ - Constructs a ActivityContext + super().__init__(version) - :param sid: The sid + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/Activities/{sid}".format( + **self._solution + ) - :returns: twilio.rest.taskrouter.v1.workspace.activity.ActivityContext - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityContext + def delete(self) -> bool: """ - return ActivityContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + Deletes the ActivityInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class ActivityPage(Page): - """ """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, response, solution): + async def delete_async(self) -> bool: """ - Initialize the ActivityPage + Asynchronous coroutine that deletes the ActivityInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The workspace_sid - :returns: twilio.rest.taskrouter.v1.workspace.activity.ActivityPage - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityPage + :returns: True if delete succeeds, False otherwise """ - super(ActivityPage, self).__init__(version, response) - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of ActivityInstance + headers = values.of({}) - :param dict payload: Payload response from the API + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance + def fetch(self) -> ActivityInstance: """ - return ActivityInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) + Fetch the ActivityInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: The fetched ActivityInstance """ - return '' + headers = values.of({}) -class ActivityContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, workspace_sid, sid): - """ - Initialize the ActivityContext + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param sid: The sid + return ActivityInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.taskrouter.v1.workspace.activity.ActivityContext - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityContext + async def fetch_async(self) -> ActivityInstance: """ - super(ActivityContext, self).__init__(version) + Asynchronous coroutine to fetch the ActivityInstance - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'sid': sid, } - self._uri = '/Workspaces/{workspace_sid}/Activities/{sid}'.format(**self._solution) - def fetch(self): + :returns: The fetched ActivityInstance """ - Fetch a ActivityInstance - :returns: Fetched ActivityInstance - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance - """ - params = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - def update(self, friendly_name=values.unset): + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> ActivityInstance: """ Update the ActivityInstance - :param unicode friendly_name: The friendly_name + :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: Updated ActivityInstance - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance + :returns: The updated ActivityInstance """ - data = values.of({'FriendlyName': friendly_name, }) + + 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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) return ActivityInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ActivityInstance: """ - Deletes the ActivityInstance + Asynchronous coroutine to update the ActivityInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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._version.delete('delete', self._uri) - def __repr__(self): + 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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ActivityInstance(InstanceResource): - """ """ +class ActivityPage(Page): - def __init__(self, version, payload, workspace_sid, sid=None): + def get_instance(self, payload: Dict[str, Any]) -> ActivityInstance: """ - Initialize the ActivityInstance + Build an instance of ActivityInstance - :returns: twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance + :param payload: Payload response from the API """ - super(ActivityInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'available': payload['available'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'friendly_name': payload['friendly_name'], - 'sid': payload['sid'], - 'workspace_sid': payload['workspace_sid'], - 'url': payload['url'], - } + return ActivityInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'sid': sid or self._properties['sid'], } + def __repr__(self) -> str: + """ + Provide a friendly representation - @property - def _proxy(self): + :returns: Machine friendly representation """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + return "" - :returns: ActivityContext for this ActivityInstance - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityContext + +class ActivityList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): """ - if self._context is None: - self._context = ActivityContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], - ) - return self._context + Initialize the ActivityList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Activity resources to read. - @property - def account_sid(self): """ - :returns: The account_sid - :rtype: unicode + 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: """ - return self._properties['account_sid'] + Create the ActivityInstance - @property - def available(self): + :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 """ - :returns: The available - :rtype: bool + + 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: """ - return self._properties['available'] + Asynchronously create the ActivityInstance - @property - def date_created(self): + :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 """ - :returns: The date_created - :rtype: datetime + + 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]: """ - return self._properties['date_created'] + 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. - @property - def date_updated(self): + :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 """ - :returns: The date_updated - :rtype: datetime + 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]: """ - return self._properties['date_updated'] + 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. - @property - def friendly_name(self): + :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 """ - :returns: The friendly_name - :rtype: unicode + 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]: """ - return self._properties['friendly_name'] + Lists ActivityInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def sid(self): + :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]: """ - :returns: The sid - :rtype: unicode + 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: """ - return self._properties['sid'] + Retrieve a single page of ActivityInstance records from the API. + Request is executed immediately - @property - def workspace_sid(self): + :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 """ - :returns: The workspace_sid - :rtype: unicode + 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: """ - return self._properties['workspace_sid'] + Asynchronously retrieve a single page of ActivityInstance records from the API. + Request is executed immediately - @property - def url(self): + :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 """ - :returns: The url - :rtype: unicode + 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: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of ActivityInstance """ - Fetch a ActivityInstance + response = self._version.domain.twilio.request("GET", target_url) + return ActivityPage(self._version, response, self._solution) - :returns: Fetched ActivityInstance - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance + async def get_page_async(self, target_url: str) -> ActivityPage: """ - return self._proxy.fetch() + 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 - def update(self, friendly_name=values.unset): + :returns: Page of ActivityInstance """ - Update the ActivityInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return ActivityPage(self._version, response, self._solution) - :param unicode friendly_name: The friendly_name + def get(self, sid: str) -> ActivityContext: + """ + Constructs a ActivityContext - :returns: Updated ActivityInstance - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance + :param sid: The SID of the Activity resource to update. """ - return self._proxy.update(friendly_name=friendly_name, ) + return ActivityContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) - def delete(self): + def __call__(self, sid: str) -> ActivityContext: """ - Deletes the ActivityInstance + Constructs a ActivityContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The SID of the Activity resource to update. """ - return self._proxy.delete() + return ActivityContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/taskrouter/v1/workspace/event.py b/twilio/rest/taskrouter/v1/workspace/event.py index b632ade8bb..1b7f289e5e 100644 --- a/twilio/rest/taskrouter/v1/workspace/event.py +++ b/twilio/rest/taskrouter/v1/workspace/event.py @@ -1,507 +1,658 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 EventList(ListResource): - """ """ +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 - def __init__(self, version, workspace_sid): + @property + def _proxy(self) -> "EventContext": """ - Initialize the EventList - - :param Version version: Version that contains the resource - :param workspace_sid: The sid + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: twilio.rest.taskrouter.v1.workspace.event.EventList - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventList + :returns: EventContext for this EventInstance """ - super(EventList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } - self._uri = '/Workspaces/{workspace_sid}/Events'.format(**self._solution) + if self._context is None: + self._context = EventContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return self._context - def stream(self, end_date=values.unset, event_type=values.unset, - minutes=values.unset, reservation_sid=values.unset, - start_date=values.unset, task_queue_sid=values.unset, - task_sid=values.unset, worker_sid=values.unset, - workflow_sid=values.unset, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the EventInstance - :param datetime end_date: The end_date - :param unicode event_type: The event_type - :param unicode minutes: The minutes - :param unicode reservation_sid: The reservation_sid - :param datetime start_date: The start_date - :param unicode task_queue_sid: The task_queue_sid - :param unicode task_sid: The task_sid - :param unicode worker_sid: The worker_sid - :param unicode workflow_sid: The workflow_sid - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.event.EventInstance] + :returns: The fetched EventInstance """ - 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, - page_size=limits['page_size'], - ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) + return self._proxy.fetch() - def list(self, end_date=values.unset, event_type=values.unset, - minutes=values.unset, reservation_sid=values.unset, - start_date=values.unset, task_queue_sid=values.unset, - task_sid=values.unset, worker_sid=values.unset, - workflow_sid=values.unset, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the EventInstance - :param datetime end_date: The end_date - :param unicode event_type: The event_type - :param unicode minutes: The minutes - :param unicode reservation_sid: The reservation_sid - :param datetime start_date: The start_date - :param unicode task_queue_sid: The task_queue_sid - :param unicode task_sid: The task_sid - :param unicode worker_sid: The worker_sid - :param unicode workflow_sid: The workflow_sid - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.event.EventInstance] + :returns: The fetched EventInstance """ - 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, - limit=limit, - page_size=page_size, - )) + return await self._proxy.fetch_async() - def page(self, end_date=values.unset, event_type=values.unset, - minutes=values.unset, reservation_sid=values.unset, - start_date=values.unset, task_queue_sid=values.unset, - task_sid=values.unset, worker_sid=values.unset, - workflow_sid=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def __repr__(self) -> str: """ - Retrieve a single page of EventInstance records from the API. - Request is executed immediately + Provide a friendly representation - :param datetime end_date: The end_date - :param unicode event_type: The event_type - :param unicode minutes: The minutes - :param unicode reservation_sid: The reservation_sid - :param datetime start_date: The start_date - :param unicode task_queue_sid: The task_queue_sid - :param unicode task_sid: The task_sid - :param unicode worker_sid: The worker_sid - :param unicode workflow_sid: The workflow_sid - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: Page of EventInstance - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventPage - """ - params = 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, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - response = self._version.page( - 'GET', - self._uri, - params=params, - ) +class EventContext(InstanceContext): - return EventPage(self._version, response, self._solution) + def __init__(self, version: Version, workspace_sid: str, sid: str): + """ + Initialize the EventContext - def get_page(self, target_url): + :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. """ - Retrieve a specific page of EventInstance records from the API. - Request is executed immediately + super().__init__(version) - :param str target_url: API-generated URL for the requested results page + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/Events/{sid}".format(**self._solution) - :returns: Page of EventInstance - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventPage + def fetch(self) -> EventInstance: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Fetch the EventInstance - return EventPage(self._version, response, self._solution) - def get(self, sid): + :returns: The fetched EventInstance """ - Constructs a EventContext - :param sid: The sid + headers = values.of({}) - :returns: twilio.rest.taskrouter.v1.workspace.event.EventContext - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventContext - """ - return EventContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + headers["Accept"] = "application/json" - def __call__(self, sid): - """ - Constructs a EventContext + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :param sid: The sid + return EventInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.taskrouter.v1.workspace.event.EventContext - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventContext + async def fetch_async(self) -> EventInstance: """ - return EventContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + Asynchronous coroutine to fetch the EventInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: The fetched EventInstance """ - return '' + headers = values.of({}) -class EventPage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): - """ - Initialize the EventPage + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The sid + return EventInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.taskrouter.v1.workspace.event.EventPage - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventPage + def __repr__(self) -> str: """ - super(EventPage, self).__init__(version, response) + Provide a friendly representation - # Path Solution - self._solution = solution + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EventPage(Page): - def get_instance(self, payload): + def get_instance(self, payload: Dict[str, Any]) -> EventInstance: """ Build an instance of EventInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.taskrouter.v1.workspace.event.EventInstance - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventInstance + :param payload: Payload response from the API """ - return EventInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) + return EventInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class EventContext(InstanceContext): - """ """ +class EventList(ListResource): - def __init__(self, version, workspace_sid, sid): + def __init__(self, version: Version, workspace_sid: str): """ - Initialize the EventContext + Initialize the EventList - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param sid: The sid + :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. - :returns: twilio.rest.taskrouter.v1.workspace.event.EventContext - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventContext """ - super(EventContext, self).__init__(version) + 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): + 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]: """ - Fetch a 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. - :returns: Fetched EventInstance - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventInstance - """ - params = values.of({}) + :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) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + :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 EventInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], - ) + 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. - def __repr__(self): - """ - Provide a friendly representation + :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: Machine friendly representation - :rtype: str + :returns: Generator that will yield up to limit results """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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. -class EventInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, workspace_sid, sid=None): - """ - Initialize the EventInstance - - :returns: twilio.rest.taskrouter.v1.workspace.event.EventInstance - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventInstance - """ - super(EventInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'actor_sid': payload['actor_sid'], - 'actor_type': payload['actor_type'], - 'actor_url': payload['actor_url'], - 'description': payload['description'], - 'event_data': payload['event_data'], - 'event_date': deserialize.iso8601_datetime(payload['event_date']), - 'event_type': payload['event_type'], - 'resource_sid': payload['resource_sid'], - 'resource_type': payload['resource_type'], - 'resource_url': payload['resource_url'], - 'sid': payload['sid'], - 'source': payload['source'], - 'source_ip_address': payload['source_ip_address'], - 'url': payload['url'], - } + :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, + ) + ) - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'sid': sid or self._properties['sid'], } + 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. - @property - def _proxy(self): + :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: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Retrieve a single page of EventInstance records from the API. + Request is executed immediately - :returns: EventContext for this EventInstance - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventContext - """ - if self._context is None: - self._context = EventContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], - ) - return self._context + :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 - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + :returns: Page of EventInstance """ - return self._properties['account_sid'] + 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, + } + ) - @property - def actor_sid(self): - """ - :returns: The actor_sid - :rtype: unicode - """ - return self._properties['actor_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def actor_type(self): - """ - :returns: The actor_type - :rtype: unicode - """ - return self._properties['actor_type'] + headers["Accept"] = "application/json" - @property - def actor_url(self): - """ - :returns: The actor_url - :rtype: unicode - """ - return self._properties['actor_url'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventPage(self._version, response, self._solution) - @property - def description(self): - """ - :returns: The description - :rtype: unicode - """ - return self._properties['description'] + 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 - @property - def event_data(self): - """ - :returns: The event_data - :rtype: unicode - """ - return self._properties['event_data'] + :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 - @property - def event_date(self): - """ - :returns: The event_date - :rtype: datetime + :returns: Page of EventInstance """ - return self._properties['event_date'] + 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, + } + ) - @property - def event_type(self): - """ - :returns: The event_type - :rtype: unicode - """ - return self._properties['event_type'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def resource_sid(self): - """ - :returns: The resource_sid - :rtype: unicode - """ - return self._properties['resource_sid'] + headers["Accept"] = "application/json" - @property - def resource_type(self): - """ - :returns: The resource_type - :rtype: unicode - """ - return self._properties['resource_type'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventPage(self._version, response, self._solution) - @property - def resource_url(self): - """ - :returns: The resource_url - :rtype: unicode + def get_page(self, target_url: str) -> EventPage: """ - return self._properties['resource_url'] + Retrieve a specific page of EventInstance records from the API. + Request is executed immediately - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + :param target_url: API-generated URL for the requested results page - @property - def source(self): - """ - :returns: The source - :rtype: unicode + :returns: Page of EventInstance """ - return self._properties['source'] + response = self._version.domain.twilio.request("GET", target_url) + return EventPage(self._version, response, self._solution) - @property - def source_ip_address(self): + async def get_page_async(self, target_url: str) -> EventPage: """ - :returns: The source_ip_address - :rtype: unicode + 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 """ - return self._properties['source_ip_address'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return EventPage(self._version, response, self._solution) - @property - def url(self): + def get(self, sid: str) -> EventContext: """ - :returns: The url - :rtype: unicode + Constructs a EventContext + + :param sid: The SID of the Event resource to fetch. """ - return self._properties['url'] + return EventContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) - def fetch(self): + def __call__(self, sid: str) -> EventContext: """ - Fetch a EventInstance + Constructs a EventContext - :returns: Fetched EventInstance - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventInstance + :param sid: The SID of the Event resource to fetch. """ - return self._proxy.fetch() + return EventContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/taskrouter/v1/workspace/task/__init__.py b/twilio/rest/taskrouter/v1/workspace/task/__init__.py index d4968b01c0..2c4516df77 100644 --- a/twilio/rest/taskrouter/v1/workspace/task/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/task/__init__.py @@ -1,698 +1,1050 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 TaskList(ListResource): - """ """ - - def __init__(self, version, workspace_sid): - """ - Initialize the TaskList - - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - - :returns: twilio.rest.taskrouter.v1.workspace.task.TaskList - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskList - """ - super(TaskList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } - self._uri = '/Workspaces/{workspace_sid}/Tasks'.format(**self._solution) - - def stream(self, priority=values.unset, assignment_status=values.unset, - workflow_sid=values.unset, workflow_name=values.unset, - task_queue_sid=values.unset, task_queue_name=values.unset, - evaluate_task_attributes=values.unset, ordering=values.unset, - has_addons=values.unset, limit=None, page_size=None): - """ - 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 unicode priority: The priority - :param unicode assignment_status: The assignment_status - :param unicode workflow_sid: The workflow_sid - :param unicode workflow_name: The workflow_name - :param unicode task_queue_sid: The task_queue_sid - :param unicode task_queue_name: The task_queue_name - :param unicode evaluate_task_attributes: The evaluate_task_attributes - :param unicode ordering: The ordering - :param bool has_addons: The has_addons - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) +class TaskInstance(InstanceResource): - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.task.TaskInstance] - """ - limits = self._version.read_limits(limit, page_size) + class Status(object): + PENDING = "pending" + RESERVED = "reserved" + ASSIGNED = "assigned" + CANCELED = "canceled" + COMPLETED = "completed" + WRAPPING = "wrapping" - 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, - ordering=ordering, - has_addons=has_addons, - page_size=limits['page_size'], + """ + :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") - return self._version.stream(page, limits['limit'], limits['page_limit']) + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid or self.sid, + } + self._context: Optional[TaskContext] = None - def list(self, priority=values.unset, assignment_status=values.unset, - workflow_sid=values.unset, workflow_name=values.unset, - task_queue_sid=values.unset, task_queue_name=values.unset, - evaluate_task_attributes=values.unset, ordering=values.unset, - has_addons=values.unset, limit=None, page_size=None): + @property + def _proxy(self) -> "TaskContext": """ - 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 unicode priority: The priority - :param unicode assignment_status: The assignment_status - :param unicode workflow_sid: The workflow_sid - :param unicode workflow_name: The workflow_name - :param unicode task_queue_sid: The task_queue_sid - :param unicode task_queue_name: The task_queue_name - :param unicode evaluate_task_attributes: The evaluate_task_attributes - :param unicode ordering: The ordering - :param bool has_addons: The has_addons - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.task.TaskInstance] + :returns: TaskContext for this TaskInstance """ - 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, - ordering=ordering, - has_addons=has_addons, - limit=limit, - page_size=page_size, - )) + if self._context is None: + self._context = TaskContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return self._context - def page(self, priority=values.unset, assignment_status=values.unset, - workflow_sid=values.unset, workflow_name=values.unset, - task_queue_sid=values.unset, task_queue_name=values.unset, - evaluate_task_attributes=values.unset, ordering=values.unset, - has_addons=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def delete(self, if_match: Union[str, object] = values.unset) -> bool: """ - Retrieve a single page of TaskInstance records from the API. - Request is executed immediately - - :param unicode priority: The priority - :param unicode assignment_status: The assignment_status - :param unicode workflow_sid: The workflow_sid - :param unicode workflow_name: The workflow_name - :param unicode task_queue_sid: The task_queue_sid - :param unicode task_queue_name: The task_queue_name - :param unicode evaluate_task_attributes: The evaluate_task_attributes - :param unicode ordering: The ordering - :param bool has_addons: The has_addons - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + Deletes the TaskInstance - :returns: Page of TaskInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskPage - """ - params = 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, - 'Ordering': ordering, - 'HasAddons': has_addons, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + :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). - response = self._version.page( - 'GET', - self._uri, - params=params, + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + if_match=if_match, ) - return TaskPage(self._version, response, self._solution) - - def get_page(self, target_url): + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: """ - Retrieve a specific page of TaskInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the TaskInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of TaskInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskPage + :returns: True if delete succeeds, False otherwise """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.delete_async( + if_match=if_match, ) - return TaskPage(self._version, response, self._solution) - - def create(self, timeout=values.unset, priority=values.unset, - task_channel=values.unset, workflow_sid=values.unset, - attributes=values.unset): + def fetch(self) -> "TaskInstance": """ - Create a new TaskInstance + Fetch the TaskInstance - :param unicode timeout: The timeout - :param unicode priority: The priority - :param unicode task_channel: The task_channel - :param unicode workflow_sid: The workflow_sid - :param unicode attributes: The attributes - :returns: Newly created TaskInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskInstance + :returns: The fetched TaskInstance """ - data = values.of({ - 'Timeout': timeout, - 'Priority': priority, - 'TaskChannel': task_channel, - 'WorkflowSid': workflow_sid, - 'Attributes': attributes, - }) + return self._proxy.fetch() - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + async def fetch_async(self) -> "TaskInstance": + """ + Asynchronous coroutine to fetch the TaskInstance - return TaskInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) - def get(self, sid): + :returns: The fetched TaskInstance """ - Constructs a TaskContext + return await self._proxy.fetch_async() - :param sid: The sid - - :returns: twilio.rest.taskrouter.v1.workspace.task.TaskContext - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskContext + 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": """ - return TaskContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + 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. - def __call__(self, sid): + :returns: The updated TaskInstance """ - Constructs a TaskContext + 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, + ) - :param sid: The 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 + """ + 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, + ) - :returns: twilio.rest.taskrouter.v1.workspace.task.TaskContext - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskContext + @property + def reservations(self) -> ReservationList: """ - return TaskContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + Access the reservations + """ + return self._proxy.reservations - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class TaskPage(Page): - """ """ +class TaskContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, workspace_sid: str, sid: str): """ - Initialize the TaskPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The workspace_sid + Initialize the TaskContext - :returns: twilio.rest.taskrouter.v1.workspace.task.TaskPage - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskPage + :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(TaskPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def delete(self, if_match: Union[str, object] = values.unset) -> bool: """ - Build an instance of TaskInstance + Deletes the TaskInstance - :param dict payload: Payload response from the API + :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: twilio.rest.taskrouter.v1.workspace.task.TaskInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskInstance + :returns: True if delete succeeds, False otherwise """ - return TaskInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) + headers = values.of( + { + "If-Match": if_match, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __repr__(self): + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the TaskInstance - :returns: Machine friendly representation - :rtype: str + :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 '' + headers = values.of( + { + "If-Match": if_match, + } + ) + headers = values.of({}) -class TaskContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, workspace_sid, sid): + def fetch(self) -> TaskInstance: """ - Initialize the TaskContext + Fetch the TaskInstance - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param sid: The sid - :returns: twilio.rest.taskrouter.v1.workspace.task.TaskContext - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskContext + :returns: The fetched TaskInstance """ - super(TaskContext, self).__init__(version) - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'sid': sid, } - self._uri = '/Workspaces/{workspace_sid}/Tasks/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - # Dependents - self._reservations = None + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return TaskInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TaskInstance: """ - Fetch a TaskInstance + Asynchronous coroutine to fetch the TaskInstance + - :returns: Fetched TaskInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskInstance + :returns: The fetched TaskInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - def update(self, attributes=values.unset, assignment_status=values.unset, - reason=values.unset, priority=values.unset, - task_channel=values.unset): + 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 unicode attributes: The attributes - :param TaskInstance.Status assignment_status: The assignment_status - :param unicode reason: The reason - :param unicode priority: The priority - :param unicode task_channel: The task_channel + :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({}) - :returns: Updated TaskInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskInstance - """ - data = values.of({ - 'Attributes': attributes, - 'AssignmentStatus': assignment_status, - 'Reason': reason, - 'Priority': priority, - 'TaskChannel': task_channel, - }) + 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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) return TaskInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - def delete(self): - """ - Deletes the TaskInstance + 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({}) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + 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): + def reservations(self) -> ReservationList: """ Access the reservations - - :returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationList - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationList """ if self._reservations is None: self._reservations = ReservationList( self._version, - workspace_sid=self._solution['workspace_sid'], - task_sid=self._solution['sid'], + self._solution["workspace_sid"], + self._solution["sid"], ) return self._reservations - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class TaskInstance(InstanceResource): - """ """ - - class Status(object): - PENDING = "pending" - RESERVED = "reserved" - ASSIGNED = "assigned" - CANCELED = "canceled" - COMPLETED = "completed" - WRAPPING = "wrapping" - - def __init__(self, version, payload, workspace_sid, sid=None): - """ - Initialize the TaskInstance - - :returns: twilio.rest.taskrouter.v1.workspace.task.TaskInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskInstance - """ - super(TaskInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'age': deserialize.integer(payload['age']), - 'assignment_status': payload['assignment_status'], - 'attributes': payload['attributes'], - 'addons': payload['addons'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'priority': deserialize.integer(payload['priority']), - 'reason': payload['reason'], - 'sid': payload['sid'], - 'task_queue_sid': payload['task_queue_sid'], - 'task_queue_friendly_name': payload['task_queue_friendly_name'], - 'task_channel_sid': payload['task_channel_sid'], - 'task_channel_unique_name': payload['task_channel_unique_name'], - 'timeout': deserialize.integer(payload['timeout']), - 'workflow_sid': payload['workflow_sid'], - 'workflow_friendly_name': payload['workflow_friendly_name'], - 'workspace_sid': payload['workspace_sid'], - 'url': payload['url'], - 'links': payload['links'], - } - - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'sid': sid or self._properties['sid'], } +class TaskPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> TaskInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of TaskInstance - :returns: TaskContext for this TaskInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = TaskContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], - ) - return self._context + return TaskInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def age(self): - """ - :returns: The age - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['age'] + return "" - @property - def assignment_status(self): - """ - :returns: The assignment_status - :rtype: TaskInstance.Status - """ - return self._properties['assignment_status'] - @property - def attributes(self): - """ - :returns: The attributes - :rtype: unicode - """ - return self._properties['attributes'] +class TaskList(ListResource): - @property - def addons(self): + def __init__(self, version: Version, workspace_sid: str): """ - :returns: The addons - :rtype: unicode - """ - return self._properties['addons'] + Initialize the TaskList - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Tasks to read. - @property - def date_updated(self): """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + super().__init__(version) - @property - def priority(self): - """ - :returns: The priority - :rtype: unicode - """ - return self._properties['priority'] + # 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"}) - @property - def reason(self): - """ - :returns: The reason - :rtype: unicode - """ - return self._properties['reason'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + headers["Accept"] = "application/json" - @property - def task_queue_sid(self): - """ - :returns: The task_queue_sid - :rtype: unicode - """ - return self._properties['task_queue_sid'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def task_queue_friendly_name(self): - """ - :returns: The task_queue_friendly_name - :rtype: unicode - """ - return self._properties['task_queue_friendly_name'] + return TaskInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) - @property - def task_channel_sid(self): - """ - :returns: The task_channel_sid - :rtype: unicode - """ - return self._properties['task_channel_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"}) - @property - def task_channel_unique_name(self): - """ - :returns: The task_channel_unique_name - :rtype: unicode - """ - return self._properties['task_channel_unique_name'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def timeout(self): - """ - :returns: The timeout - :rtype: unicode - """ - return self._properties['timeout'] + headers["Accept"] = "application/json" - @property - def workflow_sid(self): - """ - :returns: The workflow_sid - :rtype: unicode - """ - return self._properties['workflow_sid'] + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def workflow_friendly_name(self): - """ - :returns: The workflow_friendly_name - :rtype: unicode + 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]: """ - return self._properties['workflow_friendly_name'] + 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. - @property - def workspace_sid(self): + :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 """ - :returns: The workspace_sid - :rtype: unicode + 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 """ - return self._properties['workspace_sid'] + 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"], + ) - @property - def url(self): + 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]: """ - :returns: The url - :rtype: unicode + 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: """ - return self._properties['url'] + Retrieve a single page of TaskInstance records from the API. + Request is executed immediately - @property - def links(self): + :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 """ - :returns: The links - :rtype: unicode + 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 """ - return self._properties['links'] + 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, + } + ) - def fetch(self): + headers = values.of({"Content-Type": "application/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: """ - Fetch a TaskInstance + 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: Fetched TaskInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskInstance + :returns: Page of TaskInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return TaskPage(self._version, response, self._solution) - def update(self, attributes=values.unset, assignment_status=values.unset, - reason=values.unset, priority=values.unset, - task_channel=values.unset): + async def get_page_async(self, target_url: str) -> TaskPage: """ - Update the TaskInstance + Asynchronously retrieve a specific page of TaskInstance records from the API. + Request is executed immediately - :param unicode attributes: The attributes - :param TaskInstance.Status assignment_status: The assignment_status - :param unicode reason: The reason - :param unicode priority: The priority - :param unicode task_channel: The task_channel + :param target_url: API-generated URL for the requested results page - :returns: Updated TaskInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskInstance + :returns: Page of TaskInstance """ - return self._proxy.update( - attributes=attributes, - assignment_status=assignment_status, - reason=reason, - priority=priority, - task_channel=task_channel, - ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return TaskPage(self._version, response, self._solution) - def delete(self): + def get(self, sid: str) -> TaskContext: """ - Deletes the TaskInstance + Constructs a TaskContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The SID of the Task resource to update. """ - return self._proxy.delete() + return TaskContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) - @property - def reservations(self): + def __call__(self, sid: str) -> TaskContext: """ - Access the reservations + Constructs a TaskContext - :returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationList - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationList + :param sid: The SID of the Task resource to update. """ - return self._proxy.reservations + return TaskContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/taskrouter/v1/workspace/task/reservation.py b/twilio/rest/taskrouter/v1/workspace/task/reservation.py index 83c526f0fd..28cb03339a 100644 --- a/twilio/rest/taskrouter/v1/workspace/task/reservation.py +++ b/twilio/rest/taskrouter/v1/workspace/task/reservation.py @@ -1,743 +1,1351 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 ReservationList(ListResource): - """ """ - - def __init__(self, version, workspace_sid, task_sid): - """ - Initialize the ReservationList - - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param task_sid: The task_sid - - :returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationList - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationList - """ - super(ReservationList, self).__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) +class ReservationInstance(InstanceResource): - def stream(self, reservation_status=values.unset, limit=None, page_size=None): - """ - 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. + class CallStatus(object): + INITIATED = "initiated" + RINGING = "ringing" + ANSWERED = "answered" + COMPLETED = "completed" - :param ReservationInstance.Status reservation_status: The reservation_status - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + class ConferenceEvent(object): + START = "start" + END = "end" + JOIN = "join" + LEAVE = "leave" + MUTE = "mute" + HOLD = "hold" + SPEAKER = "speaker" - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationInstance] - """ - limits = self._version.read_limits(limit, page_size) + class Status(object): + PENDING = "pending" + ACCEPTED = "accepted" + REJECTED = "rejected" + TIMEOUT = "timeout" + CANCELED = "canceled" + RESCINDED = "rescinded" + WRAPPING = "wrapping" + COMPLETED = "completed" - page = self.page(reservation_status=reservation_status, page_size=limits['page_size'], ) + 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") - return self._version.stream(page, limits['limit'], limits['page_limit']) + self._solution = { + "workspace_sid": workspace_sid, + "task_sid": task_sid, + "sid": sid or self.sid, + } + self._context: Optional[ReservationContext] = None - def list(self, reservation_status=values.unset, limit=None, page_size=None): + @property + def _proxy(self) -> "ReservationContext": """ - 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: The reservation_status - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationInstance] + :returns: ReservationContext for this ReservationInstance """ - return list(self.stream(reservation_status=reservation_status, limit=limit, page_size=page_size, )) + 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 page(self, reservation_status=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch(self) -> "ReservationInstance": """ - Retrieve a single page of ReservationInstance records from the API. - Request is executed immediately + Fetch the ReservationInstance - :param ReservationInstance.Status reservation_status: The reservation_status - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationPage + :returns: The fetched ReservationInstance """ - params = values.of({ - 'ReservationStatus': reservation_status, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return ReservationPage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "ReservationInstance": """ - Retrieve a specific page of ReservationInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the ReservationInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationPage + :returns: The fetched ReservationInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ReservationPage(self._version, response, self._solution) - - def get(self, sid): + 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": """ - Constructs a ReservationContext - - :param sid: The sid + Update the ReservationInstance - :returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationContext - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationContext + :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 ReservationContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - task_sid=self._solution['task_sid'], - sid=sid, + 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, ) - def __call__(self, 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": """ - Constructs a ReservationContext - - :param sid: The sid - - :returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationContext - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationContext + 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 ReservationContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - task_sid=self._solution['task_sid'], - sid=sid, + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ReservationPage(Page): - """ """ +class ReservationContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, workspace_sid: str, task_sid: str, sid: str): """ - Initialize the ReservationPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The workspace_sid - :param task_sid: The task_sid + Initialize the ReservationContext - :returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationPage - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationPage + :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(ReservationPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def fetch(self) -> ReservationInstance: """ - Build an instance of ReservationInstance + Fetch the ReservationInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.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'], + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + async def fetch_async(self) -> ReservationInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the ReservationInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched ReservationInstance """ - return '' + headers = values.of({}) -class ReservationContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, workspace_sid, task_sid, sid): - """ - Initialize the ReservationContext + 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"], + ) - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param task_sid: The task_sid - :param sid: The 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 - :returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationContext - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationContext + :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 """ - super(ReservationContext, self).__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) + 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({}) - def fetch(self): - """ - Fetch a ReservationInstance + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match - :returns: Fetched ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationInstance - """ - params = values.of({}) + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], ) - def update(self, reservation_status=values.unset, - worker_activity_sid=values.unset, instruction=values.unset, - dequeue_post_work_activity_sid=values.unset, - dequeue_from=values.unset, dequeue_record=values.unset, - dequeue_timeout=values.unset, dequeue_to=values.unset, - dequeue_status_callback_url=values.unset, call_from=values.unset, - call_record=values.unset, call_timeout=values.unset, - call_to=values.unset, call_url=values.unset, - call_status_callback_url=values.unset, call_accept=values.unset, - redirect_call_sid=values.unset, redirect_accept=values.unset, - redirect_url=values.unset, to=values.unset, from_=values.unset, - status_callback=values.unset, status_callback_method=values.unset, - status_callback_event=values.unset, timeout=values.unset, - record=values.unset, muted=values.unset, beep=values.unset, - start_conference_on_enter=values.unset, - end_conference_on_exit=values.unset, wait_url=values.unset, - wait_method=values.unset, early_media=values.unset, - max_participants=values.unset, - conference_status_callback=values.unset, - conference_status_callback_method=values.unset, - conference_status_callback_event=values.unset, - conference_record=values.unset, conference_trim=values.unset, - recording_channels=values.unset, - recording_status_callback=values.unset, - recording_status_callback_method=values.unset, - conference_recording_status_callback=values.unset, - conference_recording_status_callback_method=values.unset, - region=values.unset, sip_auth_username=values.unset, - sip_auth_password=values.unset, - dequeue_status_callback_event=values.unset, - post_work_activity_sid=values.unset): + 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 """ - Update the ReservationInstance - :param ReservationInstance.Status reservation_status: The reservation_status - :param unicode worker_activity_sid: The worker_activity_sid - :param unicode instruction: The instruction - :param unicode dequeue_post_work_activity_sid: The dequeue_post_work_activity_sid - :param unicode dequeue_from: The dequeue_from - :param unicode dequeue_record: The dequeue_record - :param unicode dequeue_timeout: The dequeue_timeout - :param unicode dequeue_to: The dequeue_to - :param unicode dequeue_status_callback_url: The dequeue_status_callback_url - :param unicode call_from: The call_from - :param unicode call_record: The call_record - :param unicode call_timeout: The call_timeout - :param unicode call_to: The call_to - :param unicode call_url: The call_url - :param unicode call_status_callback_url: The call_status_callback_url - :param bool call_accept: The call_accept - :param unicode redirect_call_sid: The redirect_call_sid - :param bool redirect_accept: The redirect_accept - :param unicode redirect_url: The redirect_url - :param unicode to: The to - :param unicode from_: The from - :param unicode status_callback: The status_callback - :param unicode status_callback_method: The status_callback_method - :param ReservationInstance.CallStatus status_callback_event: The status_callback_event - :param unicode timeout: The timeout - :param bool record: The record - :param bool muted: The muted - :param unicode beep: The beep - :param bool start_conference_on_enter: The start_conference_on_enter - :param bool end_conference_on_exit: The end_conference_on_exit - :param unicode wait_url: The wait_url - :param unicode wait_method: The wait_method - :param bool early_media: The early_media - :param unicode max_participants: The max_participants - :param unicode conference_status_callback: The conference_status_callback - :param unicode conference_status_callback_method: The conference_status_callback_method - :param ReservationInstance.ConferenceEvent conference_status_callback_event: The conference_status_callback_event - :param unicode conference_record: The conference_record - :param unicode conference_trim: The conference_trim - :param unicode recording_channels: The recording_channels - :param unicode recording_status_callback: The recording_status_callback - :param unicode recording_status_callback_method: The recording_status_callback_method - :param unicode conference_recording_status_callback: The conference_recording_status_callback - :param unicode conference_recording_status_callback_method: The conference_recording_status_callback_method - :param unicode region: The region - :param unicode sip_auth_username: The sip_auth_username - :param unicode sip_auth_password: The sip_auth_password - :param unicode dequeue_status_callback_event: The dequeue_status_callback_event - :param unicode post_work_activity_sid: The post_work_activity_sid - - :returns: Updated ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.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': call_accept, - 'RedirectCallSid': redirect_call_sid, - 'RedirectAccept': 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': record, - 'Muted': muted, - 'Beep': beep, - 'StartConferenceOnEnter': start_conference_on_enter, - 'EndConferenceOnExit': end_conference_on_exit, - 'WaitUrl': wait_url, - 'WaitMethod': wait_method, - 'EarlyMedia': 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, - }) + 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({}) - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ReservationInstance(InstanceResource): - """ """ +class ReservationPage(Page): - class Status(object): - PENDING = "pending" - ACCEPTED = "accepted" - REJECTED = "rejected" - TIMEOUT = "timeout" - CANCELED = "canceled" - RESCINDED = "rescinded" + def get_instance(self, payload: Dict[str, Any]) -> ReservationInstance: + """ + Build an instance of ReservationInstance - class CallStatus(object): - INITIATED = "initiated" - RINGING = "ringing" - ANSWERED = "answered" - COMPLETED = "completed" + :param payload: Payload response from the API + """ + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + ) - class ConferenceEvent(object): - START = "start" - END = "end" - JOIN = "join" - LEAVE = "leave" - MUTE = "mute" - HOLD = "hold" - SPEAKER = "speaker" + def __repr__(self) -> str: + """ + Provide a friendly representation - def __init__(self, version, payload, workspace_sid, task_sid, sid=None): + :returns: Machine friendly representation """ - Initialize the ReservationInstance + return "" + + +class ReservationList(ListResource): - :returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationInstance + def __init__(self, version: Version, workspace_sid: str, task_sid: str): """ - super(ReservationInstance, self).__init__(version) + Initialize the ReservationList - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'reservation_status': payload['reservation_status'], - 'sid': payload['sid'], - 'task_sid': payload['task_sid'], - 'worker_name': payload['worker_name'], - 'worker_sid': payload['worker_sid'], - 'workspace_sid': payload['workspace_sid'], - 'url': payload['url'], - 'links': payload['links'], - } + :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. - # Context - self._context = None + """ + super().__init__(version) + + # Path Solution self._solution = { - 'workspace_sid': workspace_sid, - 'task_sid': task_sid, - 'sid': sid or self._properties['sid'], + "workspace_sid": workspace_sid, + "task_sid": task_sid, } + self._uri = "/Workspaces/{workspace_sid}/Tasks/{task_sid}/Reservations".format( + **self._solution + ) - @property - def _proxy(self): + 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]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: ReservationContext for this ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationContext - """ - 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 + :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) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['account_sid'] + limits = self._version.read_limits(limit, page_size) + page = self.page( + reservation_status=reservation_status, + worker_sid=worker_sid, + page_size=limits["page_size"], + ) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + return self._version.stream(page, limits["limit"]) - @property - def date_updated(self): + 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]: """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + 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. - @property - def reservation_status(self): - """ - :returns: The reservation_status - :rtype: ReservationInstance.Status - """ - return self._properties['reservation_status'] + :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) - @property - def sid(self): + :returns: Generator that will yield up to limit results """ - :returns: The sid - :rtype: unicode + 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]: """ - return self._properties['sid'] + Lists ReservationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def task_sid(self): + :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 """ - :returns: The task_sid - :rtype: unicode + 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]: """ - return self._properties['task_sid'] + 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. - @property - def worker_name(self): + :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 """ - :returns: The worker_name - :rtype: unicode + 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: """ - return self._properties['worker_name'] + Retrieve a single page of ReservationInstance records from the API. + Request is executed immediately - @property - def worker_sid(self): - """ - :returns: The worker_sid - :rtype: unicode + :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 """ - return self._properties['worker_sid'] + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerSid": worker_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def workspace_sid(self): + headers = values.of({"Content-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: """ - :returns: The workspace_sid - :rtype: unicode + 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 """ - return self._properties['workspace_sid'] + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerSid": worker_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def url(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + response = self._version.domain.twilio.request("GET", target_url) + return ReservationPage(self._version, response, self._solution) - @property - def links(self): + async def get_page_async(self, target_url: str) -> ReservationPage: """ - :returns: The links - :rtype: unicode + 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 """ - return self._properties['links'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return ReservationPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> ReservationContext: """ - Fetch a ReservationInstance + Constructs a ReservationContext - :returns: Fetched ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationInstance + :param sid: The SID of the TaskReservation resource to update. """ - return self._proxy.fetch() + return ReservationContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=sid, + ) - def update(self, reservation_status=values.unset, - worker_activity_sid=values.unset, instruction=values.unset, - dequeue_post_work_activity_sid=values.unset, - dequeue_from=values.unset, dequeue_record=values.unset, - dequeue_timeout=values.unset, dequeue_to=values.unset, - dequeue_status_callback_url=values.unset, call_from=values.unset, - call_record=values.unset, call_timeout=values.unset, - call_to=values.unset, call_url=values.unset, - call_status_callback_url=values.unset, call_accept=values.unset, - redirect_call_sid=values.unset, redirect_accept=values.unset, - redirect_url=values.unset, to=values.unset, from_=values.unset, - status_callback=values.unset, status_callback_method=values.unset, - status_callback_event=values.unset, timeout=values.unset, - record=values.unset, muted=values.unset, beep=values.unset, - start_conference_on_enter=values.unset, - end_conference_on_exit=values.unset, wait_url=values.unset, - wait_method=values.unset, early_media=values.unset, - max_participants=values.unset, - conference_status_callback=values.unset, - conference_status_callback_method=values.unset, - conference_status_callback_event=values.unset, - conference_record=values.unset, conference_trim=values.unset, - recording_channels=values.unset, - recording_status_callback=values.unset, - recording_status_callback_method=values.unset, - conference_recording_status_callback=values.unset, - conference_recording_status_callback_method=values.unset, - region=values.unset, sip_auth_username=values.unset, - sip_auth_password=values.unset, - dequeue_status_callback_event=values.unset, - post_work_activity_sid=values.unset): + def __call__(self, sid: str) -> ReservationContext: """ - Update the ReservationInstance + Constructs a ReservationContext - :param ReservationInstance.Status reservation_status: The reservation_status - :param unicode worker_activity_sid: The worker_activity_sid - :param unicode instruction: The instruction - :param unicode dequeue_post_work_activity_sid: The dequeue_post_work_activity_sid - :param unicode dequeue_from: The dequeue_from - :param unicode dequeue_record: The dequeue_record - :param unicode dequeue_timeout: The dequeue_timeout - :param unicode dequeue_to: The dequeue_to - :param unicode dequeue_status_callback_url: The dequeue_status_callback_url - :param unicode call_from: The call_from - :param unicode call_record: The call_record - :param unicode call_timeout: The call_timeout - :param unicode call_to: The call_to - :param unicode call_url: The call_url - :param unicode call_status_callback_url: The call_status_callback_url - :param bool call_accept: The call_accept - :param unicode redirect_call_sid: The redirect_call_sid - :param bool redirect_accept: The redirect_accept - :param unicode redirect_url: The redirect_url - :param unicode to: The to - :param unicode from_: The from - :param unicode status_callback: The status_callback - :param unicode status_callback_method: The status_callback_method - :param ReservationInstance.CallStatus status_callback_event: The status_callback_event - :param unicode timeout: The timeout - :param bool record: The record - :param bool muted: The muted - :param unicode beep: The beep - :param bool start_conference_on_enter: The start_conference_on_enter - :param bool end_conference_on_exit: The end_conference_on_exit - :param unicode wait_url: The wait_url - :param unicode wait_method: The wait_method - :param bool early_media: The early_media - :param unicode max_participants: The max_participants - :param unicode conference_status_callback: The conference_status_callback - :param unicode conference_status_callback_method: The conference_status_callback_method - :param ReservationInstance.ConferenceEvent conference_status_callback_event: The conference_status_callback_event - :param unicode conference_record: The conference_record - :param unicode conference_trim: The conference_trim - :param unicode recording_channels: The recording_channels - :param unicode recording_status_callback: The recording_status_callback - :param unicode recording_status_callback_method: The recording_status_callback_method - :param unicode conference_recording_status_callback: The conference_recording_status_callback - :param unicode conference_recording_status_callback_method: The conference_recording_status_callback_method - :param unicode region: The region - :param unicode sip_auth_username: The sip_auth_username - :param unicode sip_auth_password: The sip_auth_password - :param unicode dequeue_status_callback_event: The dequeue_status_callback_event - :param unicode post_work_activity_sid: The post_work_activity_sid - - :returns: Updated ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationInstance + :param sid: The SID of the TaskReservation resource to update. """ - return self._proxy.update( - 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, + return ReservationContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=sid, ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/taskrouter/v1/workspace/task_channel.py b/twilio/rest/taskrouter/v1/workspace/task_channel.py index 17c13f6925..3a4b0a6b9e 100644 --- a/twilio/rest/taskrouter/v1/workspace/task_channel.py +++ b/twilio/rest/taskrouter/v1/workspace/task_channel.py @@ -1,368 +1,684 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 TaskChannelList(ListResource): - """ """ +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 - def __init__(self, version, workspace_sid): + @property + def _proxy(self) -> "TaskChannelContext": """ - Initialize the TaskChannelList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid + :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 - :returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelList - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelList + def delete(self) -> bool: """ - super(TaskChannelList, self).__init__(version) + Deletes the TaskChannelInstance - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } - self._uri = '/Workspaces/{workspace_sid}/TaskChannels'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the TaskChannelInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the TaskChannelInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance] + :returns: The fetched TaskChannelInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_async(self) -> "TaskChannelInstance": """ - Retrieve a single page of TaskChannelInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the TaskChannelInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of TaskChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelPage + :returns: The fetched TaskChannelInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_async() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + def update( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> "TaskChannelInstance": + """ + Update the TaskChannelInstance - return TaskChannelPage(self._version, response, self._solution) + :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. - def get_page(self, target_url): + :returns: The updated TaskChannelInstance """ - Retrieve a specific page of TaskChannelInstance records from the API. - Request is executed immediately + return self._proxy.update( + friendly_name=friendly_name, + channel_optimized_routing=channel_optimized_routing, + ) - :param str target_url: API-generated URL for the requested results page + 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 - :returns: Page of TaskChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelPage + :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 """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + friendly_name=friendly_name, + channel_optimized_routing=channel_optimized_routing, ) - return TaskChannelPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a TaskChannelContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - :param sid: The sid +class TaskChannelContext(InstanceContext): - :returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext + def __init__(self, version: Version, workspace_sid: str, sid: str): """ - return TaskChannelContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + Initialize the TaskChannelContext - def __call__(self, sid): + :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. """ - Constructs a TaskChannelContext + super().__init__(version) - :param sid: The sid + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/TaskChannels/{sid}".format( + **self._solution + ) - :returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext + def delete(self) -> bool: """ - return TaskChannelContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + Deletes the TaskChannelInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class TaskChannelPage(Page): - """ """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, response, solution): + async def delete_async(self) -> bool: """ - Initialize the TaskChannelPage + Asynchronous coroutine that deletes the TaskChannelInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The workspace_sid - :returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelPage - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelPage + :returns: True if delete succeeds, False otherwise """ - super(TaskChannelPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TaskChannelInstance: """ - Build an instance of TaskChannelInstance + Fetch the TaskChannelInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance + :returns: The fetched TaskChannelInstance """ - return TaskChannelInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) - def __repr__(self): + 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: """ - Provide a friendly representation + Asynchronous coroutine to fetch the TaskChannelInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched TaskChannelInstance """ - return '' + headers = values.of({}) -class TaskChannelContext(InstanceContext): - """ """ + 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 __init__(self, version, workspace_sid, sid): + def update( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> TaskChannelInstance: """ - Initialize the TaskChannelContext + Update the TaskChannelInstance - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param sid: The sid + :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: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext + :returns: The updated TaskChannelInstance """ - super(TaskChannelContext, self).__init__(version) - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'sid': sid, } - self._uri = '/Workspaces/{workspace_sid}/TaskChannels/{sid}'.format(**self._solution) + data = values.of( + { + "FriendlyName": friendly_name, + "ChannelOptimizedRouting": serialize.boolean_to_string( + channel_optimized_routing + ), + } + ) + headers = values.of({}) - def fetch(self): + 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: """ - Fetch a 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: Fetched TaskChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance + :returns: The updated TaskChannelInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class TaskChannelInstance(InstanceResource): - """ """ +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 "" - def __init__(self, version, payload, workspace_sid, sid=None): + +class TaskChannelList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): """ - Initialize the TaskChannelInstance + Initialize the TaskChannelList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Task Channel to read. - :returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance """ - super(TaskChannelInstance, self).__init__(version) + super().__init__(version) - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'friendly_name': payload['friendly_name'], - 'sid': payload['sid'], - 'unique_name': payload['unique_name'], - 'workspace_sid': payload['workspace_sid'], - 'url': payload['url'], + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, } + self._uri = "/Workspaces/{workspace_sid}/TaskChannels".format(**self._solution) - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'sid': sid or self._properties['sid'], } + def create( + self, + friendly_name: str, + unique_name: str, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> TaskChannelInstance: + """ + Create the TaskChannelInstance - @property - def _proxy(self): + :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 """ - 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 - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext + 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: """ - if self._context is None: - self._context = TaskChannelContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], - ) - return self._context + Asynchronously create the TaskChannelInstance - @property - def account_sid(self): + :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]: """ - :returns: The account_sid - :rtype: unicode + 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 """ - return self._properties['account_sid'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def date_created(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TaskChannelInstance]: """ - :returns: The date_created - :rtype: datetime + 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 """ - return self._properties['date_created'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def date_updated(self): + 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 """ - :returns: The date_updated - :rtype: datetime + 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]: """ - return self._properties['date_updated'] + 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. - @property - def friendly_name(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The friendly_name - :rtype: unicode + 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: """ - return self._properties['friendly_name'] + Retrieve a single page of TaskChannelInstance records from the API. + Request is executed immediately - @property - def sid(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The sid - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['sid'] + Asynchronously retrieve a single page of TaskChannelInstance records from the API. + Request is executed immediately - @property - def unique_name(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The unique_name - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['unique_name'] + Retrieve a specific page of TaskChannelInstance records from the API. + Request is executed immediately - @property - def workspace_sid(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of TaskChannelInstance """ - :returns: The workspace_sid - :rtype: unicode + 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: """ - return self._properties['workspace_sid'] + Asynchronously retrieve a specific page of TaskChannelInstance records from the API. + Request is executed immediately - @property - def url(self): + :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: """ - :returns: The url - :rtype: unicode + Constructs a TaskChannelContext + + :param sid: The SID of the Task Channel resource to update. """ - return self._properties['url'] + return TaskChannelContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) - def fetch(self): + def __call__(self, sid: str) -> TaskChannelContext: """ - Fetch a TaskChannelInstance + Constructs a TaskChannelContext - :returns: Fetched TaskChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance + :param sid: The SID of the Task Channel resource to update. """ - return self._proxy.fetch() + return TaskChannelContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/taskrouter/v1/workspace/task_queue/__init__.py b/twilio/rest/taskrouter/v1/workspace/task_queue/__init__.py index df4b3aad27..4511a55310 100644 --- a/twilio/rest/taskrouter/v1/workspace/task_queue/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/__init__.py @@ -1,689 +1,949 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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_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 TaskQueueList(ListResource): - """ """ +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, +) - def __init__(self, version, workspace_sid): - """ - Initialize the TaskQueueList - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid +class TaskQueueInstance(InstanceResource): - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueList - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueList - """ - super(TaskQueueList, self).__init__(version) + class TaskOrder(object): + FIFO = "FIFO" + LIFO = "LIFO" - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } - self._uri = '/Workspaces/{workspace_sid}/TaskQueues'.format(**self._solution) + """ + :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") - # Components - self._statistics = None + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid or self.sid, + } + self._context: Optional[TaskQueueContext] = None - def stream(self, friendly_name=values.unset, - evaluate_worker_attributes=values.unset, worker_sid=values.unset, - limit=None, page_size=None): + @property + def _proxy(self) -> "TaskQueueContext": """ - 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. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param unicode friendly_name: The friendly_name - :param unicode evaluate_worker_attributes: The evaluate_worker_attributes - :param unicode worker_sid: The worker_sid - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the TaskQueueInstance - page = self.page( - friendly_name=friendly_name, - evaluate_worker_attributes=evaluate_worker_attributes, - worker_sid=worker_sid, - page_size=limits['page_size'], - ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, friendly_name=values.unset, - evaluate_worker_attributes=values.unset, worker_sid=values.unset, - limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists TaskQueueInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the TaskQueueInstance - :param unicode friendly_name: The friendly_name - :param unicode evaluate_worker_attributes: The evaluate_worker_attributes - :param unicode worker_sid: The worker_sid - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream( - friendly_name=friendly_name, - evaluate_worker_attributes=evaluate_worker_attributes, - worker_sid=worker_sid, - limit=limit, - page_size=page_size, - )) + return await self._proxy.delete_async() - def page(self, friendly_name=values.unset, - evaluate_worker_attributes=values.unset, worker_sid=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "TaskQueueInstance": """ - Retrieve a single page of TaskQueueInstance records from the API. - Request is executed immediately + Fetch the TaskQueueInstance - :param unicode friendly_name: The friendly_name - :param unicode evaluate_worker_attributes: The evaluate_worker_attributes - :param unicode worker_sid: The worker_sid - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of TaskQueueInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueuePage + :returns: The fetched TaskQueueInstance """ - params = values.of({ - 'FriendlyName': friendly_name, - 'EvaluateWorkerAttributes': evaluate_worker_attributes, - 'WorkerSid': worker_sid, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + async def fetch_async(self) -> "TaskQueueInstance": + """ + Asynchronous coroutine to fetch the TaskQueueInstance - return TaskQueuePage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched TaskQueueInstance """ - Retrieve a specific page of TaskQueueInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_async() - :param str target_url: API-generated URL for the requested results page + 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 - :returns: Page of TaskQueueInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueuePage + :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 """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, ) - return TaskQueuePage(self._version, response, self._solution) - - def create(self, friendly_name, reservation_activity_sid, - assignment_activity_sid, target_workers=values.unset, - max_reserved_workers=values.unset, task_order=values.unset): + 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": """ - Create a new TaskQueueInstance + Asynchronous coroutine to update the TaskQueueInstance - :param unicode friendly_name: The friendly_name - :param unicode reservation_activity_sid: The reservation_activity_sid - :param unicode assignment_activity_sid: The assignment_activity_sid - :param unicode target_workers: The target_workers - :param unicode max_reserved_workers: The max_reserved_workers - :param TaskQueueInstance.TaskOrder task_order: The task_order + :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: Newly created TaskQueueInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance + :returns: The updated TaskQueueInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'ReservationActivitySid': reservation_activity_sid, - 'AssignmentActivitySid': assignment_activity_sid, - 'TargetWorkers': target_workers, - 'MaxReservedWorkers': max_reserved_workers, - 'TaskOrder': task_order, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, + 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, ) - return TaskQueueInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) - @property - def statistics(self): + def cumulative_statistics(self) -> TaskQueueCumulativeStatisticsList: """ - Access the statistics - - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queues_statistics.TaskQueuesStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queues_statistics.TaskQueuesStatisticsList + Access the cumulative_statistics """ - if self._statistics is None: - self._statistics = TaskQueuesStatisticsList( - self._version, - workspace_sid=self._solution['workspace_sid'], - ) - return self._statistics + return self._proxy.cumulative_statistics - def get(self, sid): + @property + def real_time_statistics(self) -> TaskQueueRealTimeStatisticsList: """ - Constructs a TaskQueueContext - - :param sid: The sid - - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueContext - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueContext + Access the real_time_statistics """ - return TaskQueueContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + return self._proxy.real_time_statistics - def __call__(self, sid): + @property + def statistics(self) -> TaskQueueStatisticsList: """ - Constructs a TaskQueueContext - - :param sid: The sid - - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueContext - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueContext + Access the statistics """ - return TaskQueueContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + return self._proxy.statistics - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class TaskQueuePage(Page): - """ """ +class TaskQueueContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, workspace_sid: str, sid: str): """ - Initialize the TaskQueuePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The workspace_sid + Initialize the TaskQueueContext - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueuePage - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueuePage + :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(TaskQueuePage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of TaskQueueInstance + Deletes the TaskQueueInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance + :returns: True if delete succeeds, False otherwise """ - return TaskQueueInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the TaskQueueInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class TaskQueueContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, workspace_sid, sid): + def fetch(self) -> TaskQueueInstance: """ - Initialize the TaskQueueContext + Fetch the TaskQueueInstance - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param sid: The sid - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueContext - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueContext + :returns: The fetched TaskQueueInstance """ - super(TaskQueueContext, self).__init__(version) - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'sid': sid, } - self._uri = '/Workspaces/{workspace_sid}/TaskQueues/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - # Dependents - self._statistics = None - self._real_time_statistics = None - self._cumulative_statistics = None + 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"], + ) - def fetch(self): + async def fetch_async(self) -> TaskQueueInstance: """ - Fetch a TaskQueueInstance + Asynchronous coroutine to fetch the TaskQueueInstance - :returns: Fetched TaskQueueInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance + + :returns: The fetched TaskQueueInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - def update(self, friendly_name=values.unset, target_workers=values.unset, - reservation_activity_sid=values.unset, - assignment_activity_sid=values.unset, - max_reserved_workers=values.unset, task_order=values.unset): + 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 unicode friendly_name: The friendly_name - :param unicode target_workers: The target_workers - :param unicode reservation_activity_sid: The reservation_activity_sid - :param unicode assignment_activity_sid: The assignment_activity_sid - :param unicode max_reserved_workers: The max_reserved_workers - :param TaskQueueInstance.TaskOrder task_order: The task_order - - :returns: Updated TaskQueueInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.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, - }) + :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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) return TaskQueueInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - def delete(self): - """ - Deletes the TaskQueueInstance + 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({}) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + 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 statistics(self): + def cumulative_statistics(self) -> TaskQueueCumulativeStatisticsList: """ - Access the statistics - - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsList + Access the cumulative_statistics """ - if self._statistics is None: - self._statistics = TaskQueueStatisticsList( + if self._cumulative_statistics is None: + self._cumulative_statistics = TaskQueueCumulativeStatisticsList( self._version, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['sid'], + self._solution["workspace_sid"], + self._solution["sid"], ) - return self._statistics + return self._cumulative_statistics @property - def real_time_statistics(self): + def real_time_statistics(self) -> TaskQueueRealTimeStatisticsList: """ Access the real_time_statistics - - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsList """ if self._real_time_statistics is None: self._real_time_statistics = TaskQueueRealTimeStatisticsList( self._version, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['sid'], + self._solution["workspace_sid"], + self._solution["sid"], ) return self._real_time_statistics @property - def cumulative_statistics(self): + def statistics(self) -> TaskQueueStatisticsList: """ - Access the cumulative_statistics - - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsList + Access the statistics """ - if self._cumulative_statistics is None: - self._cumulative_statistics = TaskQueueCumulativeStatisticsList( + if self._statistics is None: + self._statistics = TaskQueueStatisticsList( self._version, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['sid'], + self._solution["workspace_sid"], + self._solution["sid"], ) - return self._cumulative_statistics + return self._statistics - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class TaskQueueInstance(InstanceResource): - """ """ - - class TaskOrder(object): - FIFO = "FIFO" - LIFO = "LIFO" - - def __init__(self, version, payload, workspace_sid, sid=None): - """ - Initialize the TaskQueueInstance - - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance - """ - super(TaskQueueInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'assignment_activity_sid': payload['assignment_activity_sid'], - 'assignment_activity_name': payload['assignment_activity_name'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'friendly_name': payload['friendly_name'], - 'max_reserved_workers': deserialize.integer(payload['max_reserved_workers']), - 'reservation_activity_sid': payload['reservation_activity_sid'], - 'reservation_activity_name': payload['reservation_activity_name'], - 'sid': payload['sid'], - 'target_workers': payload['target_workers'], - 'task_order': payload['task_order'], - 'url': payload['url'], - 'workspace_sid': payload['workspace_sid'], - 'links': payload['links'], - } - - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'sid': sid or self._properties['sid'], } +class TaskQueuePage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> TaskQueueInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of TaskQueueInstance - :returns: TaskQueueContext for this TaskQueueInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = TaskQueueContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], - ) - return self._context + return TaskQueueInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def assignment_activity_sid(self): - """ - :returns: The assignment_activity_sid - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['assignment_activity_sid'] + return "" - @property - def assignment_activity_name(self): - """ - :returns: The assignment_activity_name - :rtype: unicode - """ - return self._properties['assignment_activity_name'] - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] +class TaskQueueList(ListResource): - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime + def __init__(self, version: Version, workspace_sid: str): """ - return self._properties['date_updated'] + Initialize the TaskQueueList - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskQueue to read. - @property - def max_reserved_workers(self): """ - :returns: The max_reserved_workers - :rtype: unicode - """ - return self._properties['max_reserved_workers'] + super().__init__(version) - @property - def reservation_activity_sid(self): - """ - :returns: The reservation_activity_sid - :rtype: unicode - """ - return self._properties['reservation_activity_sid'] + # 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"}) - @property - def reservation_activity_name(self): - """ - :returns: The reservation_activity_name - :rtype: unicode - """ - return self._properties['reservation_activity_name'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + headers["Accept"] = "application/json" - @property - def target_workers(self): - """ - :returns: The target_workers - :rtype: unicode - """ - return self._properties['target_workers'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def task_order(self): + 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]: """ - :returns: The task_order - :rtype: TaskQueueInstance.TaskOrder + 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 """ - return self._properties['task_order'] + 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"], + ) - @property - def url(self): + 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]: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + 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"], + ) - @property - def workspace_sid(self): + 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]: """ - :returns: The workspace_sid - :rtype: unicode + 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: """ - return self._properties['workspace_sid'] + Retrieve a single page of TaskQueueInstance records from the API. + Request is executed immediately - @property - def links(self): + :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 """ - :returns: The links - :rtype: unicode + 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 """ - return self._properties['links'] + 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"}) - def fetch(self): + 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: """ - Fetch a TaskQueueInstance + 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: Fetched TaskQueueInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance + :returns: Page of TaskQueueInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return TaskQueuePage(self._version, response, self._solution) - def update(self, friendly_name=values.unset, target_workers=values.unset, - reservation_activity_sid=values.unset, - assignment_activity_sid=values.unset, - max_reserved_workers=values.unset, task_order=values.unset): + async def get_page_async(self, target_url: str) -> TaskQueuePage: """ - Update the TaskQueueInstance + Asynchronously retrieve a specific page of TaskQueueInstance records from the API. + Request is executed immediately - :param unicode friendly_name: The friendly_name - :param unicode target_workers: The target_workers - :param unicode reservation_activity_sid: The reservation_activity_sid - :param unicode assignment_activity_sid: The assignment_activity_sid - :param unicode max_reserved_workers: The max_reserved_workers - :param TaskQueueInstance.TaskOrder task_order: The task_order + :param target_url: API-generated URL for the requested results page - :returns: Updated TaskQueueInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance + :returns: Page of 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, - ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return TaskQueuePage(self._version, response, self._solution) - def delete(self): + @property + def bulk_real_time_statistics(self) -> TaskQueueBulkRealTimeStatisticsList: """ - Deletes the TaskQueueInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool + Access the bulk_real_time_statistics """ - return self._proxy.delete() + 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): + def statistics(self) -> TaskQueuesStatisticsList: """ Access the statistics - - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsList """ - return self._proxy.statistics + if self._statistics is None: + self._statistics = TaskQueuesStatisticsList( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + return self._statistics - @property - def real_time_statistics(self): + def get(self, sid: str) -> TaskQueueContext: """ - Access the real_time_statistics + Constructs a TaskQueueContext - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsList + :param sid: The SID of the TaskQueue resource to update. """ - return self._proxy.real_time_statistics + return TaskQueueContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) - @property - def cumulative_statistics(self): + def __call__(self, sid: str) -> TaskQueueContext: """ - Access the cumulative_statistics + Constructs a TaskQueueContext - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsList + :param sid: The SID of the TaskQueue resource to update. """ - return self._proxy.cumulative_statistics + return TaskQueueContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 ( + "".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 "" 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 index 6abdefe11b..ef851c755a 100644 --- 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 @@ -1,443 +1,376 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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.page import Page - - -class TaskQueueCumulativeStatisticsList(ListResource): - """ """ - - def __init__(self, version, workspace_sid, task_queue_sid): - """ - Initialize the TaskQueueCumulativeStatisticsList +from twilio.base.version import Version - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param task_queue_sid: The task_queue_sid - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsList - """ - super(TaskQueueCumulativeStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'task_queue_sid': task_queue_sid, } - - def get(self): - """ - Constructs a TaskQueueCumulativeStatisticsContext - - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsContext - """ - return TaskQueueCumulativeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['task_queue_sid'], +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") ) - - def __call__(self): - """ - Constructs a TaskQueueCumulativeStatisticsContext - - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsContext - """ - return TaskQueueCumulativeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['task_queue_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.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") - def __repr__(self): - """ - Provide a friendly representation + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } + self._context: Optional[TaskQueueCumulativeStatisticsContext] = None - :returns: Machine friendly representation - :rtype: str + @property + def _proxy(self) -> "TaskQueueCumulativeStatisticsContext": """ - return '' - + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context -class TaskQueueCumulativeStatisticsPage(Page): - """ """ + :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 __init__(self, version, response, 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": """ - Initialize the TaskQueueCumulativeStatisticsPage + Fetch the TaskQueueCumulativeStatisticsInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The workspace_sid - :param task_queue_sid: The task_queue_sid + :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: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsPage - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsPage + :returns: The fetched TaskQueueCumulativeStatisticsInstance """ - super(TaskQueueCumulativeStatisticsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + 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, + ) - def get_instance(self, payload): + 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": """ - Build an instance of TaskQueueCumulativeStatisticsInstance + Asynchronous coroutine to fetch the TaskQueueCumulativeStatisticsInstance - :param dict payload: Payload response from the API + :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: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsInstance + :returns: The fetched TaskQueueCumulativeStatisticsInstance """ - return TaskQueueCumulativeStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['task_queue_sid'], + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) class TaskQueueCumulativeStatisticsContext(InstanceContext): - """ """ - def __init__(self, version, workspace_sid, task_queue_sid): + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): """ Initialize the TaskQueueCumulativeStatisticsContext - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param task_queue_sid: The task_queue_sid - - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.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(TaskQueueCumulativeStatisticsContext, self).__init__(version) + 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) + 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=values.unset, minutes=values.unset, - start_date=values.unset, task_channel=values.unset, - split_by_wait_time=values.unset): - """ - Fetch a TaskQueueCumulativeStatisticsInstance + 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, + } + ) - :param datetime end_date: The end_date - :param unicode minutes: The minutes - :param datetime start_date: The start_date - :param unicode task_channel: The task_channel - :param unicode split_by_wait_time: The split_by_wait_time + headers = values.of({}) - :returns: Fetched TaskQueueCumulativeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsInstance - """ - params = 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["Accept"] = "application/json" payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], ) - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class TaskQueueCumulativeStatisticsInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, workspace_sid, task_queue_sid): - """ - Initialize the TaskQueueCumulativeStatisticsInstance - - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsInstance - """ - super(TaskQueueCumulativeStatisticsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'avg_task_acceptance_time': deserialize.integer(payload['avg_task_acceptance_time']), - 'start_time': deserialize.iso8601_datetime(payload['start_time']), - 'end_time': deserialize.iso8601_datetime(payload['end_time']), - 'reservations_created': deserialize.integer(payload['reservations_created']), - 'reservations_accepted': deserialize.integer(payload['reservations_accepted']), - 'reservations_rejected': deserialize.integer(payload['reservations_rejected']), - 'reservations_timed_out': deserialize.integer(payload['reservations_timed_out']), - 'reservations_canceled': deserialize.integer(payload['reservations_canceled']), - 'reservations_rescinded': deserialize.integer(payload['reservations_rescinded']), - 'split_by_wait_time': payload['split_by_wait_time'], - 'task_queue_sid': payload['task_queue_sid'], - 'wait_duration_until_accepted': payload['wait_duration_until_accepted'], - 'wait_duration_until_canceled': payload['wait_duration_until_canceled'], - 'tasks_canceled': deserialize.integer(payload['tasks_canceled']), - 'tasks_completed': deserialize.integer(payload['tasks_completed']), - 'tasks_deleted': deserialize.integer(payload['tasks_deleted']), - 'tasks_entered': deserialize.integer(payload['tasks_entered']), - 'tasks_moved': deserialize.integer(payload['tasks_moved']), - 'workspace_sid': payload['workspace_sid'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'task_queue_sid': task_queue_sid, } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsContext - """ - 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 - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def avg_task_acceptance_time(self): - """ - :returns: The avg_task_acceptance_time - :rtype: unicode - """ - return self._properties['avg_task_acceptance_time'] - - @property - def start_time(self): - """ - :returns: The start_time - :rtype: datetime - """ - return self._properties['start_time'] - - @property - def end_time(self): - """ - :returns: The end_time - :rtype: datetime - """ - return self._properties['end_time'] - - @property - def reservations_created(self): - """ - :returns: The reservations_created - :rtype: unicode - """ - return self._properties['reservations_created'] - - @property - def reservations_accepted(self): - """ - :returns: The reservations_accepted - :rtype: unicode - """ - return self._properties['reservations_accepted'] - - @property - def reservations_rejected(self): - """ - :returns: The reservations_rejected - :rtype: unicode - """ - return self._properties['reservations_rejected'] + 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, + } + ) - @property - def reservations_timed_out(self): - """ - :returns: The reservations_timed_out - :rtype: unicode - """ - return self._properties['reservations_timed_out'] + headers = values.of({}) - @property - def reservations_canceled(self): - """ - :returns: The reservations_canceled - :rtype: unicode - """ - return self._properties['reservations_canceled'] + headers["Accept"] = "application/json" - @property - def reservations_rescinded(self): - """ - :returns: The reservations_rescinded - :rtype: unicode - """ - return self._properties['reservations_rescinded'] + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) - @property - def split_by_wait_time(self): - """ - :returns: The split_by_wait_time - :rtype: dict - """ - return self._properties['split_by_wait_time'] + return TaskQueueCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) - @property - def task_queue_sid(self): - """ - :returns: The task_queue_sid - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['task_queue_sid'] + Provide a friendly representation - @property - def wait_duration_until_accepted(self): - """ - :returns: The wait_duration_until_accepted - :rtype: dict + :returns: Machine friendly representation """ - return self._properties['wait_duration_until_accepted'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) - @property - def wait_duration_until_canceled(self): - """ - :returns: The wait_duration_until_canceled - :rtype: dict - """ - return self._properties['wait_duration_until_canceled'] - @property - def tasks_canceled(self): - """ - :returns: The tasks_canceled - :rtype: unicode - """ - return self._properties['tasks_canceled'] +class TaskQueueCumulativeStatisticsList(ListResource): - @property - def tasks_completed(self): + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): """ - :returns: The tasks_completed - :rtype: unicode - """ - return self._properties['tasks_completed'] + Initialize the TaskQueueCumulativeStatisticsList - @property - def tasks_deleted(self): - """ - :returns: The tasks_deleted - :rtype: unicode - """ - return self._properties['tasks_deleted'] + :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. - @property - def tasks_entered(self): """ - :returns: The tasks_entered - :rtype: unicode - """ - return self._properties['tasks_entered'] + super().__init__(version) - @property - def tasks_moved(self): - """ - :returns: The tasks_moved - :rtype: unicode - """ - return self._properties['tasks_moved'] + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } - @property - def workspace_sid(self): - """ - :returns: The workspace_sid - :rtype: unicode + def get(self) -> TaskQueueCumulativeStatisticsContext: """ - return self._properties['workspace_sid'] + Constructs a TaskQueueCumulativeStatisticsContext - @property - def url(self): - """ - :returns: The url - :rtype: unicode """ - return self._properties['url'] + return TaskQueueCumulativeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) - def fetch(self, end_date=values.unset, minutes=values.unset, - start_date=values.unset, task_channel=values.unset, - split_by_wait_time=values.unset): + def __call__(self) -> TaskQueueCumulativeStatisticsContext: """ - Fetch a TaskQueueCumulativeStatisticsInstance - - :param datetime end_date: The end_date - :param unicode minutes: The minutes - :param datetime start_date: The start_date - :param unicode task_channel: The task_channel - :param unicode split_by_wait_time: The split_by_wait_time + Constructs a TaskQueueCumulativeStatisticsContext - :returns: Fetched TaskQueueCumulativeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.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, + return TaskQueueCumulativeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 index 7e8398c865..c4eb30ddc0 100644 --- 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 @@ -1,328 +1,291 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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.page import Page - - -class TaskQueueRealTimeStatisticsList(ListResource): - """ """ - - def __init__(self, version, workspace_sid, task_queue_sid): - """ - Initialize the TaskQueueRealTimeStatisticsList - - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param task_queue_sid: The task_queue_sid +from twilio.base.version import Version - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsList - """ - super(TaskQueueRealTimeStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'task_queue_sid': task_queue_sid, } - - def get(self): - """ - Constructs a TaskQueueRealTimeStatisticsContext - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsContext - """ - return TaskQueueRealTimeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['task_queue_sid'], +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" ) - - def __call__(self): - """ - Constructs a TaskQueueRealTimeStatisticsContext - - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsContext - """ - return TaskQueueRealTimeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['task_queue_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.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") - def __repr__(self): - """ - Provide a friendly representation + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } + self._context: Optional[TaskQueueRealTimeStatisticsContext] = None - :returns: Machine friendly representation - :rtype: str + @property + def _proxy(self) -> "TaskQueueRealTimeStatisticsContext": """ - return '' - + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context -class TaskQueueRealTimeStatisticsPage(Page): - """ """ + :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 __init__(self, version, response, solution): + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> "TaskQueueRealTimeStatisticsInstance": """ - Initialize the TaskQueueRealTimeStatisticsPage + Fetch the TaskQueueRealTimeStatisticsInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The workspace_sid - :param task_queue_sid: The task_queue_sid + :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: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsPage - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsPage + :returns: The fetched TaskQueueRealTimeStatisticsInstance """ - super(TaskQueueRealTimeStatisticsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch( + task_channel=task_channel, + ) - def get_instance(self, payload): + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> "TaskQueueRealTimeStatisticsInstance": """ - Build an instance of TaskQueueRealTimeStatisticsInstance + Asynchronous coroutine to fetch the TaskQueueRealTimeStatisticsInstance - :param dict payload: Payload response from the API + :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: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsInstance + :returns: The fetched TaskQueueRealTimeStatisticsInstance """ - return TaskQueueRealTimeStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['task_queue_sid'], + return await self._proxy.fetch_async( + task_channel=task_channel, ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) class TaskQueueRealTimeStatisticsContext(InstanceContext): - """ """ - def __init__(self, version, workspace_sid, task_queue_sid): + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): """ Initialize the TaskQueueRealTimeStatisticsContext - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param task_queue_sid: The task_queue_sid - - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.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(TaskQueueRealTimeStatisticsContext, self).__init__(version) + 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) + 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=values.unset): + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> TaskQueueRealTimeStatisticsInstance: """ - Fetch a TaskQueueRealTimeStatisticsInstance + Fetch the TaskQueueRealTimeStatisticsInstance - :param unicode task_channel: The task_channel + :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: Fetched TaskQueueRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsInstance + :returns: The fetched TaskQueueRealTimeStatisticsInstance """ - params = values.of({'TaskChannel': task_channel, }) + + data = values.of( + { + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], ) - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> TaskQueueRealTimeStatisticsInstance: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - + Asynchronous coroutine to fetch the TaskQueueRealTimeStatisticsInstance -class TaskQueueRealTimeStatisticsInstance(InstanceResource): - """ """ + :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`. - def __init__(self, version, payload, workspace_sid, task_queue_sid): + :returns: The fetched TaskQueueRealTimeStatisticsInstance """ - Initialize the TaskQueueRealTimeStatisticsInstance - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsInstance - """ - super(TaskQueueRealTimeStatisticsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'activity_statistics': payload['activity_statistics'], - 'longest_task_waiting_age': deserialize.integer(payload['longest_task_waiting_age']), - 'task_queue_sid': payload['task_queue_sid'], - 'tasks_by_priority': payload['tasks_by_priority'], - 'tasks_by_status': payload['tasks_by_status'], - 'total_available_workers': deserialize.integer(payload['total_available_workers']), - 'total_eligible_workers': deserialize.integer(payload['total_eligible_workers']), - 'total_tasks': deserialize.integer(payload['total_tasks']), - 'workspace_sid': payload['workspace_sid'], - 'url': payload['url'], - } + data = values.of( + { + "TaskChannel": task_channel, + } + ) - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'task_queue_sid': task_queue_sid, } + headers = values.of({}) - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + headers["Accept"] = "application/json" - :returns: TaskQueueRealTimeStatisticsContext for this TaskQueueRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsContext - """ - 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 + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + return TaskQueueRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) - @property - def activity_statistics(self): - """ - :returns: The activity_statistics - :rtype: dict + def __repr__(self) -> str: """ - return self._properties['activity_statistics'] + Provide a friendly representation - @property - def longest_task_waiting_age(self): - """ - :returns: The longest_task_waiting_age - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['longest_task_waiting_age'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) - @property - def task_queue_sid(self): - """ - :returns: The task_queue_sid - :rtype: unicode - """ - return self._properties['task_queue_sid'] - @property - def tasks_by_priority(self): - """ - :returns: The tasks_by_priority - :rtype: dict - """ - return self._properties['tasks_by_priority'] +class TaskQueueRealTimeStatisticsList(ListResource): - @property - def tasks_by_status(self): - """ - :returns: The tasks_by_status - :rtype: dict + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): """ - return self._properties['tasks_by_status'] + Initialize the TaskQueueRealTimeStatisticsList - @property - def total_available_workers(self): - """ - :returns: The total_available_workers - :rtype: unicode - """ - return self._properties['total_available_workers'] + :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. - @property - def total_eligible_workers(self): - """ - :returns: The total_eligible_workers - :rtype: unicode """ - return self._properties['total_eligible_workers'] + super().__init__(version) - @property - def total_tasks(self): - """ - :returns: The total_tasks - :rtype: unicode - """ - return self._properties['total_tasks'] + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } - @property - def workspace_sid(self): + def get(self) -> TaskQueueRealTimeStatisticsContext: """ - :returns: The workspace_sid - :rtype: unicode - """ - return self._properties['workspace_sid'] + Constructs a TaskQueueRealTimeStatisticsContext - @property - def url(self): - """ - :returns: The url - :rtype: unicode """ - return self._properties['url'] + return TaskQueueRealTimeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) - def fetch(self, task_channel=values.unset): + def __call__(self) -> TaskQueueRealTimeStatisticsContext: """ - Fetch a TaskQueueRealTimeStatisticsInstance - - :param unicode task_channel: The task_channel + Constructs a TaskQueueRealTimeStatisticsContext - :returns: Fetched TaskQueueRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsInstance """ - return self._proxy.fetch(task_channel=task_channel, ) + return TaskQueueRealTimeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 index 8c7e3949c8..2d5d631069 100644 --- a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_statistics.py @@ -1,307 +1,306 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import serialize -from twilio.base import values +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.page import Page - - -class TaskQueueStatisticsList(ListResource): - """ """ +from twilio.base.version import Version - def __init__(self, version, workspace_sid, task_queue_sid): - """ - Initialize the TaskQueueStatisticsList - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param task_queue_sid: The task_queue_sid +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 - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsList + @property + def _proxy(self) -> "TaskQueueStatisticsContext": """ - super(TaskQueueStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'task_queue_sid': task_queue_sid, } + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def get(self): + :returns: TaskQueueStatisticsContext for this TaskQueueStatisticsInstance """ - Constructs a TaskQueueStatisticsContext + 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 - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsContext + 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": """ - return TaskQueueStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['task_queue_sid'], - ) + Fetch the TaskQueueStatisticsInstance - def __call__(self): - """ - Constructs a TaskQueueStatisticsContext + :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: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsContext + :returns: The fetched TaskQueueStatisticsInstance """ - return TaskQueueStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['task_queue_sid'], + 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, ) - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class TaskQueueStatisticsPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the TaskQueueStatisticsPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The workspace_sid - :param task_queue_sid: The task_queue_sid - - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsPage - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsPage - """ - super(TaskQueueStatisticsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): + 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": """ - Build an instance of TaskQueueStatisticsInstance + Asynchronous coroutine to fetch the TaskQueueStatisticsInstance - :param dict payload: Payload response from the API + :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: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsInstance + :returns: The fetched TaskQueueStatisticsInstance """ - return TaskQueueStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['task_queue_sid'], + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) class TaskQueueStatisticsContext(InstanceContext): - """ """ - def __init__(self, version, workspace_sid, task_queue_sid): + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): """ Initialize the TaskQueueStatisticsContext - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param task_queue_sid: The task_queue_sid - - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.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(TaskQueueStatisticsContext, self).__init__(version) + 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) + 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=values.unset, minutes=values.unset, - start_date=values.unset, task_channel=values.unset, - split_by_wait_time=values.unset): - """ - Fetch a TaskQueueStatisticsInstance + 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, + } + ) - :param datetime end_date: The end_date - :param unicode minutes: The minutes - :param datetime start_date: The start_date - :param unicode task_channel: The task_channel - :param unicode split_by_wait_time: The split_by_wait_time + headers = values.of({}) - :returns: Fetched TaskQueueStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsInstance - """ - params = 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["Accept"] = "application/json" payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], ) - def __repr__(self): - """ - Provide a friendly representation + 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, + } + ) - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + headers = values.of({}) + headers["Accept"] = "application/json" -class TaskQueueStatisticsInstance(InstanceResource): - """ """ + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) - def __init__(self, version, payload, workspace_sid, task_queue_sid): - """ - Initialize the TaskQueueStatisticsInstance + return TaskQueueStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsInstance + def __repr__(self) -> str: """ - super(TaskQueueStatisticsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'cumulative': payload['cumulative'], - 'realtime': payload['realtime'], - 'task_queue_sid': payload['task_queue_sid'], - 'workspace_sid': payload['workspace_sid'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'task_queue_sid': task_queue_sid, } + Provide a friendly representation - @property - def _proxy(self): + :returns: Machine friendly representation """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: TaskQueueStatisticsContext for this TaskQueueStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsContext - """ - 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 - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] +class TaskQueueStatisticsList(ListResource): - @property - def cumulative(self): + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): """ - :returns: The cumulative - :rtype: dict - """ - return self._properties['cumulative'] + Initialize the TaskQueueStatisticsList - @property - def realtime(self): - """ - :returns: The realtime - :rtype: dict - """ - return self._properties['realtime'] + :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. - @property - def task_queue_sid(self): """ - :returns: The task_queue_sid - :rtype: unicode - """ - return self._properties['task_queue_sid'] + super().__init__(version) - @property - def workspace_sid(self): - """ - :returns: The workspace_sid - :rtype: unicode - """ - return self._properties['workspace_sid'] + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } - @property - def url(self): + def get(self) -> TaskQueueStatisticsContext: """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] + Constructs a TaskQueueStatisticsContext - def fetch(self, end_date=values.unset, minutes=values.unset, - start_date=values.unset, task_channel=values.unset, - split_by_wait_time=values.unset): """ - Fetch a TaskQueueStatisticsInstance + return TaskQueueStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) - :param datetime end_date: The end_date - :param unicode minutes: The minutes - :param datetime start_date: The start_date - :param unicode task_channel: The task_channel - :param unicode split_by_wait_time: The split_by_wait_time + def __call__(self) -> TaskQueueStatisticsContext: + """ + Constructs a TaskQueueStatisticsContext - :returns: Fetched TaskQueueStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.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, + return TaskQueueStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 index c01b50e1df..036f6ad92b 100644 --- a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queues_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queues_statistics.py @@ -1,65 +1,133 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import serialize -from twilio.base import values +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 "".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 "" + + class TaskQueuesStatisticsList(ListResource): - """ """ - def __init__(self, version, workspace_sid): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the TaskQueuesStatisticsList - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskQueues to read. - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queues_statistics.TaskQueuesStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queues_statistics.TaskQueuesStatisticsList """ - super(TaskQueuesStatisticsList, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'workspace_sid': workspace_sid, } - self._uri = '/Workspaces/{workspace_sid}/TaskQueues/Statistics'.format(**self._solution) + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/TaskQueues/Statistics".format( + **self._solution + ) - def stream(self, end_date=values.unset, friendly_name=values.unset, - minutes=values.unset, start_date=values.unset, - task_channel=values.unset, split_by_wait_time=values.unset, - limit=None, page_size=None): + 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: The end_date - :param unicode friendly_name: The friendly_name - :param unicode minutes: The minutes - :param datetime start_date: The start_date - :param unicode task_channel: The task_channel - :param unicode split_by_wait_time: The split_by_wait_time - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :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 - :rtype: list[twilio.rest.taskrouter.v1.workspace.task_queue.task_queues_statistics.TaskQueuesStatisticsInstance] """ limits = self._version.read_limits(limit, page_size) - page = self.page( end_date=end_date, friendly_name=friendly_name, @@ -67,230 +135,275 @@ def stream(self, end_date=values.unset, friendly_name=values.unset, start_date=start_date, task_channel=task_channel, split_by_wait_time=split_by_wait_time, - page_size=limits['page_size'], + page_size=limits["page_size"], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, end_date=values.unset, friendly_name=values.unset, - minutes=values.unset, start_date=values.unset, - task_channel=values.unset, split_by_wait_time=values.unset, limit=None, - page_size=None): - """ - Lists TaskQueuesStatisticsInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + 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: The end_date - :param unicode friendly_name: The friendly_name - :param unicode minutes: The minutes - :param datetime start_date: The start_date - :param unicode task_channel: The task_channel - :param unicode split_by_wait_time: The split_by_wait_time - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + :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 - :rtype: list[twilio.rest.taskrouter.v1.workspace.task_queue.task_queues_statistics.TaskQueuesStatisticsInstance] """ - return list(self.stream( + 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, - limit=limit, - page_size=page_size, - )) - - def page(self, end_date=values.unset, friendly_name=values.unset, - minutes=values.unset, start_date=values.unset, - task_channel=values.unset, split_by_wait_time=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of TaskQueuesStatisticsInstance records from the API. - Request is executed immediately + page_size=limits["page_size"], + ) - :param datetime end_date: The end_date - :param unicode friendly_name: The friendly_name - :param unicode minutes: The minutes - :param datetime start_date: The start_date - :param unicode task_channel: The task_channel - :param unicode split_by_wait_time: The split_by_wait_time - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + return self._version.stream_async(page, limits["limit"]) - :returns: Page of TaskQueuesStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queues_statistics.TaskQueuesStatisticsPage + 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]: """ - params = 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, - }) + Lists TaskQueuesStatisticsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - response = self._version.page( - 'GET', - self._uri, - params=params, + :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, + ) ) - return TaskQueuesStatisticsPage(self._version, response, self._solution) + 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. - def get_page(self, target_url): + :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 specific page of TaskQueuesStatisticsInstance records from the API. + Retrieve a single page of TaskQueuesStatisticsInstance records from the API. Request is executed immediately - :param str target_url: API-generated URL for the requested results page + :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 - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queues_statistics.TaskQueuesStatisticsPage """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, + } ) - return TaskQueuesStatisticsPage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class TaskQueuesStatisticsPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the TaskQueuesStatisticsPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The workspace_sid + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queues_statistics.TaskQueuesStatisticsPage - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queues_statistics.TaskQueuesStatisticsPage - """ - super(TaskQueuesStatisticsPage, self).__init__(version, response) + headers["Accept"] = "application/json" - # Path Solution - self._solution = solution + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TaskQueuesStatisticsPage(self._version, response, self._solution) - def get_instance(self, payload): - """ - Build an instance of TaskQueuesStatisticsInstance + 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 dict payload: Payload response from the API + :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: twilio.rest.taskrouter.v1.workspace.task_queue.task_queues_statistics.TaskQueuesStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queues_statistics.TaskQueuesStatisticsInstance + :returns: Page of TaskQueuesStatisticsInstance """ - return TaskQueuesStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], + 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, + } ) - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers["Accept"] = "application/json" -class TaskQueuesStatisticsInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, workspace_sid): - """ - Initialize the TaskQueuesStatisticsInstance + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TaskQueuesStatisticsPage(self._version, response, self._solution) - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queues_statistics.TaskQueuesStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queues_statistics.TaskQueuesStatisticsInstance + def get_page(self, target_url: str) -> TaskQueuesStatisticsPage: """ - super(TaskQueuesStatisticsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'cumulative': payload['cumulative'], - 'realtime': payload['realtime'], - 'task_queue_sid': payload['task_queue_sid'], - 'workspace_sid': payload['workspace_sid'], - } + Retrieve a specific page of TaskQueuesStatisticsInstance records from the API. + Request is executed immediately - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, } + :param target_url: API-generated URL for the requested results page - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def cumulative(self): - """ - :returns: The cumulative - :rtype: dict + :returns: Page of TaskQueuesStatisticsInstance """ - return self._properties['cumulative'] + response = self._version.domain.twilio.request("GET", target_url) + return TaskQueuesStatisticsPage(self._version, response, self._solution) - @property - def realtime(self): - """ - :returns: The realtime - :rtype: dict + async def get_page_async(self, target_url: str) -> TaskQueuesStatisticsPage: """ - return self._properties['realtime'] + Asynchronously retrieve a specific page of TaskQueuesStatisticsInstance records from the API. + Request is executed immediately - @property - def task_queue_sid(self): - """ - :returns: The task_queue_sid - :rtype: unicode - """ - return self._properties['task_queue_sid'] + :param target_url: API-generated URL for the requested results page - @property - def workspace_sid(self): - """ - :returns: The workspace_sid - :rtype: unicode + :returns: Page of TaskQueuesStatisticsInstance """ - return self._properties['workspace_sid'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return TaskQueuesStatisticsPage(self._version, response, self._solution) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/taskrouter/v1/workspace/worker/__init__.py b/twilio/rest/taskrouter/v1/workspace/worker/__init__.py index a41c1afabb..38aede84bb 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/__init__.py @@ -1,725 +1,1009 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 +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 WorkerList(ListResource): - """ """ +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 - def __init__(self, version, workspace_sid): + @property + def _proxy(self) -> "WorkerContext": """ - Initialize the WorkerList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid + :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 - :returns: twilio.rest.taskrouter.v1.workspace.worker.WorkerList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerList + def delete(self, if_match: Union[str, object] = values.unset) -> bool: """ - super(WorkerList, self).__init__(version) + Deletes the WorkerInstance - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } - self._uri = '/Workspaces/{workspace_sid}/Workers'.format(**self._solution) + :param if_match: The If-Match HTTP request header - # Components - self._statistics = None + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + if_match=if_match, + ) - def stream(self, activity_name=values.unset, activity_sid=values.unset, - available=values.unset, friendly_name=values.unset, - target_workers_expression=values.unset, task_queue_name=values.unset, - task_queue_sid=values.unset, limit=None, page_size=None): + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: """ - 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. + Asynchronous coroutine that deletes the WorkerInstance - :param unicode activity_name: The activity_name - :param unicode activity_sid: The activity_sid - :param unicode available: The available - :param unicode friendly_name: The friendly_name - :param unicode target_workers_expression: The target_workers_expression - :param unicode task_queue_name: The task_queue_name - :param unicode task_queue_sid: The task_queue_sid - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :param if_match: The If-Match HTTP request header - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance] + :returns: True if delete succeeds, False otherwise """ - 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, - page_size=limits['page_size'], + return await self._proxy.delete_async( + if_match=if_match, ) - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, activity_name=values.unset, activity_sid=values.unset, - available=values.unset, friendly_name=values.unset, - target_workers_expression=values.unset, task_queue_name=values.unset, - task_queue_sid=values.unset, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the WorkerInstance - :param unicode activity_name: The activity_name - :param unicode activity_sid: The activity_sid - :param unicode available: The available - :param unicode friendly_name: The friendly_name - :param unicode target_workers_expression: The target_workers_expression - :param unicode task_queue_name: The task_queue_name - :param unicode task_queue_sid: The task_queue_sid - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance] + :returns: The fetched WorkerInstance """ - 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, - limit=limit, - page_size=page_size, - )) + return self._proxy.fetch() - def page(self, activity_name=values.unset, activity_sid=values.unset, - available=values.unset, friendly_name=values.unset, - target_workers_expression=values.unset, task_queue_name=values.unset, - task_queue_sid=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + async def fetch_async(self) -> "WorkerInstance": """ - Retrieve a single page of WorkerInstance records from the API. - Request is executed immediately - - :param unicode activity_name: The activity_name - :param unicode activity_sid: The activity_sid - :param unicode available: The available - :param unicode friendly_name: The friendly_name - :param unicode target_workers_expression: The target_workers_expression - :param unicode task_queue_name: The task_queue_name - :param unicode task_queue_sid: The task_queue_sid - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + Asynchronous coroutine to fetch the WorkerInstance - :returns: Page of WorkerInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerPage - """ - params = 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, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return WorkerPage(self._version, response, self._solution) + :returns: The fetched WorkerInstance + """ + return await self._proxy.fetch_async() - def get_page(self, target_url): + 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": """ - Retrieve a specific page of WorkerInstance records from the API. - Request is executed immediately + Update the WorkerInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of WorkerInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerPage + :returns: The updated WorkerInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + if_match=if_match, + activity_sid=activity_sid, + attributes=attributes, + friendly_name=friendly_name, + reject_pending_reservations=reject_pending_reservations, ) - return WorkerPage(self._version, response, self._solution) - - def create(self, friendly_name, activity_sid=values.unset, - attributes=values.unset): + 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": """ - Create a new WorkerInstance + Asynchronous coroutine to update the WorkerInstance - :param unicode friendly_name: The friendly_name - :param unicode activity_sid: The activity_sid - :param unicode attributes: The attributes + :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: Newly created WorkerInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance + :returns: The updated WorkerInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'ActivitySid': activity_sid, - 'Attributes': attributes, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, + 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, ) - return WorkerInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) - @property - def statistics(self): + def reservations(self) -> ReservationList: """ - Access the statistics - - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsList + Access the reservations """ - if self._statistics is None: - self._statistics = WorkersStatisticsList( - self._version, - workspace_sid=self._solution['workspace_sid'], - ) - return self._statistics + return self._proxy.reservations - def get(self, sid): + @property + def worker_channels(self) -> WorkerChannelList: """ - Constructs a WorkerContext - - :param sid: The sid - - :returns: twilio.rest.taskrouter.v1.workspace.worker.WorkerContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerContext + Access the worker_channels """ - return WorkerContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + return self._proxy.worker_channels - def __call__(self, sid): + @property + def statistics(self) -> WorkerStatisticsList: """ - Constructs a WorkerContext - - :param sid: The sid - - :returns: twilio.rest.taskrouter.v1.workspace.worker.WorkerContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerContext + Access the statistics """ - return WorkerContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + return self._proxy.statistics - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class WorkerPage(Page): - """ """ +class WorkerContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, workspace_sid: str, sid: str): """ - Initialize the WorkerPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The workspace_sid + Initialize the WorkerContext - :returns: twilio.rest.taskrouter.v1.workspace.worker.WorkerPage - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerPage + :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(WorkerPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workers/{sid}".format(**self._solution) - def get_instance(self, payload): + 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: """ - Build an instance of WorkerInstance + Deletes the WorkerInstance - :param dict payload: Payload response from the API + :param if_match: The If-Match HTTP request header - :returns: twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance + :returns: True if delete succeeds, False otherwise """ - return WorkerInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) + headers = values.of( + { + "If-Match": if_match, + } + ) + + headers = values.of({}) - def __repr__(self): + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the WorkerInstance - :returns: Machine friendly representation - :rtype: str + :param if_match: The If-Match HTTP request header + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of( + { + "If-Match": if_match, + } + ) + headers = values.of({}) -class WorkerContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, workspace_sid, sid): + def fetch(self) -> WorkerInstance: """ - Initialize the WorkerContext + Fetch the WorkerInstance - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param sid: The sid - :returns: twilio.rest.taskrouter.v1.workspace.worker.WorkerContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerContext + :returns: The fetched WorkerInstance """ - super(WorkerContext, self).__init__(version) - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'sid': sid, } - self._uri = '/Workspaces/{workspace_sid}/Workers/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - # Dependents - self._real_time_statistics = None - self._cumulative_statistics = None - self._statistics = None - self._reservations = None - self._worker_channels = None + 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"], + ) - def fetch(self): + async def fetch_async(self) -> WorkerInstance: """ - Fetch a WorkerInstance + Asynchronous coroutine to fetch the WorkerInstance - :returns: Fetched WorkerInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance + + :returns: The fetched WorkerInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - def update(self, activity_sid=values.unset, attributes=values.unset, - friendly_name=values.unset): + 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 unicode activity_sid: The activity_sid - :param unicode attributes: The attributes - :param unicode friendly_name: The friendly_name + :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: Updated WorkerInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance + :returns: The updated WorkerInstance """ - data = values.of({ - 'ActivitySid': activity_sid, - 'Attributes': attributes, - 'FriendlyName': friendly_name, - }) + + 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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) return WorkerInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - def delete(self): - """ - Deletes the WorkerInstance + 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({}) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + 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 real_time_statistics(self): + def reservations(self) -> ReservationList: """ - Access the real_time_statistics - - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsList + Access the reservations """ - if self._real_time_statistics is None: - self._real_time_statistics = WorkersRealTimeStatisticsList( + if self._reservations is None: + self._reservations = ReservationList( self._version, - workspace_sid=self._solution['workspace_sid'], + self._solution["workspace_sid"], + self._solution["sid"], ) - return self._real_time_statistics + return self._reservations @property - def cumulative_statistics(self): + def worker_channels(self) -> WorkerChannelList: """ - Access the cumulative_statistics - - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsList + Access the worker_channels """ - if self._cumulative_statistics is None: - self._cumulative_statistics = WorkersCumulativeStatisticsList( + if self._worker_channels is None: + self._worker_channels = WorkerChannelList( self._version, - workspace_sid=self._solution['workspace_sid'], + self._solution["workspace_sid"], + self._solution["sid"], ) - return self._cumulative_statistics + return self._worker_channels @property - def statistics(self): + def statistics(self) -> WorkerStatisticsList: """ Access the statistics - - :returns: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsList """ if self._statistics is None: self._statistics = WorkerStatisticsList( self._version, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['sid'], + self._solution["workspace_sid"], + self._solution["sid"], ) return self._statistics - @property - def reservations(self): + def __repr__(self) -> str: """ - Access the reservations + Provide a friendly representation - :returns: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationList + :returns: Machine friendly representation """ - if self._reservations is None: - self._reservations = ReservationList( - self._version, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['sid'], - ) - return self._reservations + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def worker_channels(self): + +class WorkerPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WorkerInstance: """ - Access the worker_channels + Build an instance of WorkerInstance - :returns: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelList + :param payload: Payload response from the API """ - if self._worker_channels is None: - self._worker_channels = WorkerChannelList( - self._version, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['sid'], - ) - return self._worker_channels + return WorkerInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - + return "" -class WorkerInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, workspace_sid, sid=None): - """ - Initialize the WorkerInstance - - :returns: twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance - """ - super(WorkerInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'activity_name': payload['activity_name'], - 'activity_sid': payload['activity_sid'], - 'attributes': payload['attributes'], - 'available': payload['available'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_status_changed': deserialize.iso8601_datetime(payload['date_status_changed']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'friendly_name': payload['friendly_name'], - 'sid': payload['sid'], - 'workspace_sid': payload['workspace_sid'], - 'url': payload['url'], - 'links': payload['links'], - } - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'sid': sid or self._properties['sid'], } +class WorkerList(ListResource): - @property - def _proxy(self): + def __init__(self, version: Version, workspace_sid: str): """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Initialize the WorkerList - :returns: WorkerContext for this WorkerInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerContext - """ - if self._context is None: - self._context = WorkerContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], - ) - return self._context + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Workers to read. - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode """ - return self._properties['account_sid'] + super().__init__(version) - @property - def activity_name(self): - """ - :returns: The activity_name - :rtype: unicode - """ - return self._properties['activity_name'] + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workers".format(**self._solution) - @property - def activity_sid(self): - """ - :returns: The activity_sid - :rtype: unicode - """ - return self._properties['activity_sid'] + self._cumulative_statistics: Optional[WorkersCumulativeStatisticsList] = None + self._real_time_statistics: Optional[WorkersRealTimeStatisticsList] = None + self._statistics: Optional[WorkersStatisticsList] = None - @property - def attributes(self): + def create( + self, + friendly_name: str, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> WorkerInstance: """ - :returns: The attributes - :rtype: unicode - """ - return self._properties['attributes'] + Create the WorkerInstance - @property - def available(self): - """ - :returns: The available - :rtype: bool - """ - return self._properties['available'] + :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 {}. - @property - def date_created(self): + :returns: The created WorkerInstance """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - @property - def date_status_changed(self): - """ - :returns: The date_status_changed - :rtype: datetime - """ - return self._properties['date_status_changed'] + data = values.of( + { + "FriendlyName": friendly_name, + "ActivitySid": activity_sid, + "Attributes": attributes, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] + headers["Accept"] = "application/json" - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def workspace_sid(self): - """ - :returns: The workspace_sid - :rtype: unicode + 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: """ - return self._properties['workspace_sid'] + Asynchronously create the WorkerInstance - @property - def url(self): + :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 """ - :returns: The url - :rtype: unicode + + 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]: """ - return self._properties['url'] + 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. - @property - def links(self): + :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 """ - :returns: The links - :rtype: unicode + 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 """ - return self._properties['links'] + 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"], + ) - def fetch(self): + 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]: """ - Fetch a 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. - :returns: Fetched WorkerInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance + :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: """ - return self._proxy.fetch() + Retrieve a single page of WorkerInstance records from the API. + Request is executed immediately - def update(self, activity_sid=values.unset, attributes=values.unset, - friendly_name=values.unset): + :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 """ - Update the 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 unicode activity_sid: The activity_sid - :param unicode attributes: The attributes - :param unicode friendly_name: The friendly_name + :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: Updated WorkerInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance + :returns: Page of WorkerInstance """ - return self._proxy.update( - activity_sid=activity_sid, - attributes=attributes, - friendly_name=friendly_name, + 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, + } ) - def delete(self): + headers = values.of({"Content-Type": "application/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: """ - Deletes the WorkerInstance + Retrieve a specific page of WorkerInstance records from the API. + Request is executed immediately - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param target_url: API-generated URL for the requested results page + + :returns: Page of WorkerInstance """ - return self._proxy.delete() + response = self._version.domain.twilio.request("GET", target_url) + return WorkerPage(self._version, response, self._solution) - @property - def real_time_statistics(self): + async def get_page_async(self, target_url: str) -> WorkerPage: """ - Access the real_time_statistics + 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: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsList + :returns: Page of WorkerInstance """ - return self._proxy.real_time_statistics + response = await self._version.domain.twilio.request_async("GET", target_url) + return WorkerPage(self._version, response, self._solution) @property - def cumulative_statistics(self): + 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 - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsList + @property + def real_time_statistics(self) -> WorkersRealTimeStatisticsList: """ - return self._proxy.cumulative_statistics + 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): + def statistics(self) -> WorkersStatisticsList: """ Access the statistics - - :returns: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsList """ - return self._proxy.statistics + if self._statistics is None: + self._statistics = WorkersStatisticsList( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + return self._statistics - @property - def reservations(self): + def get(self, sid: str) -> WorkerContext: """ - Access the reservations + Constructs a WorkerContext - :returns: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationList + :param sid: The SID of the Worker resource to update. """ - return self._proxy.reservations + return WorkerContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) - @property - def worker_channels(self): + def __call__(self, sid: str) -> WorkerContext: """ - Access the worker_channels + Constructs a WorkerContext - :returns: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelList + :param sid: The SID of the Worker resource to update. """ - return self._proxy.worker_channels + return WorkerContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/taskrouter/v1/workspace/worker/reservation.py b/twilio/rest/taskrouter/v1/workspace/worker/reservation.py index d8c06ae308..7f24057806 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/reservation.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/reservation.py @@ -1,743 +1,1294 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 ReservationList(ListResource): - """ """ - - def __init__(self, version, workspace_sid, worker_sid): - """ - Initialize the ReservationList - - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param worker_sid: The worker_sid - - :returns: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationList - """ - super(ReservationList, self).__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) +class ReservationInstance(InstanceResource): - def stream(self, reservation_status=values.unset, limit=None, page_size=None): - """ - 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. + class CallStatus(object): + INITIATED = "initiated" + RINGING = "ringing" + ANSWERED = "answered" + COMPLETED = "completed" - :param ReservationInstance.Status reservation_status: The reservation_status - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + class ConferenceEvent(object): + START = "start" + END = "end" + JOIN = "join" + LEAVE = "leave" + MUTE = "mute" + HOLD = "hold" + SPEAKER = "speaker" - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationInstance] - """ - limits = self._version.read_limits(limit, page_size) + class Status(object): + PENDING = "pending" + ACCEPTED = "accepted" + REJECTED = "rejected" + TIMEOUT = "timeout" + CANCELED = "canceled" + RESCINDED = "rescinded" + WRAPPING = "wrapping" + COMPLETED = "completed" - page = self.page(reservation_status=reservation_status, page_size=limits['page_size'], ) + """ + :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") - return self._version.stream(page, limits['limit'], limits['page_limit']) + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + "sid": sid or self.sid, + } + self._context: Optional[ReservationContext] = None - def list(self, reservation_status=values.unset, limit=None, page_size=None): + @property + def _proxy(self) -> "ReservationContext": """ - 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: The reservation_status - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationInstance] + :returns: ReservationContext for this ReservationInstance """ - return list(self.stream(reservation_status=reservation_status, limit=limit, page_size=page_size, )) + 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 page(self, reservation_status=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch(self) -> "ReservationInstance": """ - Retrieve a single page of ReservationInstance records from the API. - Request is executed immediately + Fetch the ReservationInstance - :param ReservationInstance.Status reservation_status: The reservation_status - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationPage + :returns: The fetched ReservationInstance """ - params = values.of({ - 'ReservationStatus': reservation_status, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return ReservationPage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "ReservationInstance": """ - Retrieve a specific page of ReservationInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the ReservationInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationPage + :returns: The fetched ReservationInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ReservationPage(self._version, response, self._solution) - - def get(self, sid): + 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": """ - Constructs a ReservationContext - - :param sid: The sid + Update the ReservationInstance - :returns: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationContext + :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 ReservationContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['worker_sid'], - sid=sid, + 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, ) - def __call__(self, 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": """ - Constructs a ReservationContext - - :param sid: The sid - - :returns: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationContext + 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 ReservationContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['worker_sid'], - sid=sid, + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ReservationPage(Page): - """ """ +class ReservationContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, workspace_sid: str, worker_sid: str, sid: str): """ - Initialize the ReservationPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The workspace_sid - :param worker_sid: The worker_sid + Initialize the ReservationContext - :returns: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationPage - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationPage + :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(ReservationPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def fetch(self) -> ReservationInstance: """ - Build an instance of ReservationInstance + Fetch the ReservationInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.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'], + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + async def fetch_async(self) -> ReservationInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the ReservationInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched ReservationInstance """ - return '' + headers = values.of({}) -class ReservationContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, workspace_sid, worker_sid, sid): - """ - Initialize the ReservationContext + 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"], + ) - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param worker_sid: The worker_sid - :param sid: The 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 - :returns: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationContext + :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 """ - super(ReservationContext, self).__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) + 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({}) - def fetch(self): - """ - Fetch a ReservationInstance + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match - :returns: Fetched ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationInstance - """ - params = values.of({}) + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], ) - def update(self, reservation_status=values.unset, - worker_activity_sid=values.unset, instruction=values.unset, - dequeue_post_work_activity_sid=values.unset, - dequeue_from=values.unset, dequeue_record=values.unset, - dequeue_timeout=values.unset, dequeue_to=values.unset, - dequeue_status_callback_url=values.unset, call_from=values.unset, - call_record=values.unset, call_timeout=values.unset, - call_to=values.unset, call_url=values.unset, - call_status_callback_url=values.unset, call_accept=values.unset, - redirect_call_sid=values.unset, redirect_accept=values.unset, - redirect_url=values.unset, to=values.unset, from_=values.unset, - status_callback=values.unset, status_callback_method=values.unset, - status_callback_event=values.unset, timeout=values.unset, - record=values.unset, muted=values.unset, beep=values.unset, - start_conference_on_enter=values.unset, - end_conference_on_exit=values.unset, wait_url=values.unset, - wait_method=values.unset, early_media=values.unset, - max_participants=values.unset, - conference_status_callback=values.unset, - conference_status_callback_method=values.unset, - conference_status_callback_event=values.unset, - conference_record=values.unset, conference_trim=values.unset, - recording_channels=values.unset, - recording_status_callback=values.unset, - recording_status_callback_method=values.unset, - conference_recording_status_callback=values.unset, - conference_recording_status_callback_method=values.unset, - region=values.unset, sip_auth_username=values.unset, - sip_auth_password=values.unset, - dequeue_status_callback_event=values.unset, - post_work_activity_sid=values.unset): + 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 """ - Update the ReservationInstance - :param ReservationInstance.Status reservation_status: The reservation_status - :param unicode worker_activity_sid: The worker_activity_sid - :param unicode instruction: The instruction - :param unicode dequeue_post_work_activity_sid: The dequeue_post_work_activity_sid - :param unicode dequeue_from: The dequeue_from - :param unicode dequeue_record: The dequeue_record - :param unicode dequeue_timeout: The dequeue_timeout - :param unicode dequeue_to: The dequeue_to - :param unicode dequeue_status_callback_url: The dequeue_status_callback_url - :param unicode call_from: The call_from - :param unicode call_record: The call_record - :param unicode call_timeout: The call_timeout - :param unicode call_to: The call_to - :param unicode call_url: The call_url - :param unicode call_status_callback_url: The call_status_callback_url - :param bool call_accept: The call_accept - :param unicode redirect_call_sid: The redirect_call_sid - :param bool redirect_accept: The redirect_accept - :param unicode redirect_url: The redirect_url - :param unicode to: The to - :param unicode from_: The from - :param unicode status_callback: The status_callback - :param unicode status_callback_method: The status_callback_method - :param ReservationInstance.CallStatus status_callback_event: The status_callback_event - :param unicode timeout: The timeout - :param bool record: The record - :param bool muted: The muted - :param unicode beep: The beep - :param bool start_conference_on_enter: The start_conference_on_enter - :param bool end_conference_on_exit: The end_conference_on_exit - :param unicode wait_url: The wait_url - :param unicode wait_method: The wait_method - :param bool early_media: The early_media - :param unicode max_participants: The max_participants - :param unicode conference_status_callback: The conference_status_callback - :param unicode conference_status_callback_method: The conference_status_callback_method - :param ReservationInstance.ConferenceEvent conference_status_callback_event: The conference_status_callback_event - :param unicode conference_record: The conference_record - :param unicode conference_trim: The conference_trim - :param unicode recording_channels: The recording_channels - :param unicode recording_status_callback: The recording_status_callback - :param unicode recording_status_callback_method: The recording_status_callback_method - :param unicode conference_recording_status_callback: The conference_recording_status_callback - :param unicode conference_recording_status_callback_method: The conference_recording_status_callback_method - :param unicode region: The region - :param unicode sip_auth_username: The sip_auth_username - :param unicode sip_auth_password: The sip_auth_password - :param unicode dequeue_status_callback_event: The dequeue_status_callback_event - :param unicode post_work_activity_sid: The post_work_activity_sid - - :returns: Updated ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.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': call_accept, - 'RedirectCallSid': redirect_call_sid, - 'RedirectAccept': 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': record, - 'Muted': muted, - 'Beep': beep, - 'StartConferenceOnEnter': start_conference_on_enter, - 'EndConferenceOnExit': end_conference_on_exit, - 'WaitUrl': wait_url, - 'WaitMethod': wait_method, - 'EarlyMedia': 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, - }) + 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({}) - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class ReservationInstance(InstanceResource): - """ """ - class Status(object): - PENDING = "pending" - ACCEPTED = "accepted" - REJECTED = "rejected" - TIMEOUT = "timeout" - CANCELED = "canceled" - RESCINDED = "rescinded" +class ReservationPage(Page): - class CallStatus(object): - INITIATED = "initiated" - RINGING = "ringing" - ANSWERED = "answered" - COMPLETED = "completed" + def get_instance(self, payload: Dict[str, Any]) -> ReservationInstance: + """ + Build an instance of ReservationInstance - class ConferenceEvent(object): - START = "start" - END = "end" - JOIN = "join" - LEAVE = "leave" - MUTE = "mute" - HOLD = "hold" - SPEAKER = "speaker" + :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 __init__(self, version, payload, workspace_sid, worker_sid, sid=None): + def __repr__(self) -> str: """ - Initialize the ReservationInstance + Provide a friendly representation - :returns: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationInstance + :returns: Machine friendly representation """ - super(ReservationInstance, self).__init__(version) + return "" - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'reservation_status': payload['reservation_status'], - 'sid': payload['sid'], - 'task_sid': payload['task_sid'], - 'worker_name': payload['worker_name'], - 'worker_sid': payload['worker_sid'], - 'workspace_sid': payload['workspace_sid'], - 'url': payload['url'], - 'links': payload['links'], - } - # Context - self._context = None - self._solution = { - 'workspace_sid': workspace_sid, - 'worker_sid': worker_sid, - 'sid': sid or self._properties['sid'], - } +class ReservationList(ListResource): - @property - def _proxy(self): + def __init__(self, version: Version, workspace_sid: str, worker_sid: str): """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: ReservationContext for this ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationContext """ - 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'], + 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 ) - return self._context + ) - @property - def account_sid(self): + def stream( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ReservationInstance]: """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + 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. - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + :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) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime + :returns: Generator that will yield up to limit results """ - return self._properties['date_updated'] + limits = self._version.read_limits(limit, page_size) + page = self.page( + reservation_status=reservation_status, page_size=limits["page_size"] + ) - @property - def reservation_status(self): - """ - :returns: The reservation_status - :rtype: ReservationInstance.Status + 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]: """ - return self._properties['reservation_status'] + 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. - @property - def sid(self): + :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 """ - :returns: The sid - :rtype: unicode + 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]: """ - return self._properties['sid'] + Lists ReservationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def task_sid(self): + :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 """ - :returns: The task_sid - :rtype: unicode + 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]: """ - return self._properties['task_sid'] + 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. - @property - def worker_name(self): + :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 """ - :returns: The worker_name - :rtype: unicode + 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: """ - return self._properties['worker_name'] + Retrieve a single page of ReservationInstance records from the API. + Request is executed immediately - @property - def worker_sid(self): - """ - :returns: The worker_sid - :rtype: unicode + :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 """ - return self._properties['worker_sid'] + data = values.of( + { + "ReservationStatus": reservation_status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def workspace_sid(self): + headers = values.of({"Content-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: """ - :returns: The workspace_sid - :rtype: unicode + 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 """ - return self._properties['workspace_sid'] + data = values.of( + { + "ReservationStatus": reservation_status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def url(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + response = self._version.domain.twilio.request("GET", target_url) + return ReservationPage(self._version, response, self._solution) - @property - def links(self): + async def get_page_async(self, target_url: str) -> ReservationPage: """ - :returns: The links - :rtype: unicode + 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 """ - return self._properties['links'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return ReservationPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> ReservationContext: """ - Fetch a ReservationInstance + Constructs a ReservationContext - :returns: Fetched ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationInstance + :param sid: The SID of the WorkerReservation resource to update. """ - return self._proxy.fetch() + return ReservationContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=sid, + ) - def update(self, reservation_status=values.unset, - worker_activity_sid=values.unset, instruction=values.unset, - dequeue_post_work_activity_sid=values.unset, - dequeue_from=values.unset, dequeue_record=values.unset, - dequeue_timeout=values.unset, dequeue_to=values.unset, - dequeue_status_callback_url=values.unset, call_from=values.unset, - call_record=values.unset, call_timeout=values.unset, - call_to=values.unset, call_url=values.unset, - call_status_callback_url=values.unset, call_accept=values.unset, - redirect_call_sid=values.unset, redirect_accept=values.unset, - redirect_url=values.unset, to=values.unset, from_=values.unset, - status_callback=values.unset, status_callback_method=values.unset, - status_callback_event=values.unset, timeout=values.unset, - record=values.unset, muted=values.unset, beep=values.unset, - start_conference_on_enter=values.unset, - end_conference_on_exit=values.unset, wait_url=values.unset, - wait_method=values.unset, early_media=values.unset, - max_participants=values.unset, - conference_status_callback=values.unset, - conference_status_callback_method=values.unset, - conference_status_callback_event=values.unset, - conference_record=values.unset, conference_trim=values.unset, - recording_channels=values.unset, - recording_status_callback=values.unset, - recording_status_callback_method=values.unset, - conference_recording_status_callback=values.unset, - conference_recording_status_callback_method=values.unset, - region=values.unset, sip_auth_username=values.unset, - sip_auth_password=values.unset, - dequeue_status_callback_event=values.unset, - post_work_activity_sid=values.unset): + def __call__(self, sid: str) -> ReservationContext: """ - Update the ReservationInstance + Constructs a ReservationContext - :param ReservationInstance.Status reservation_status: The reservation_status - :param unicode worker_activity_sid: The worker_activity_sid - :param unicode instruction: The instruction - :param unicode dequeue_post_work_activity_sid: The dequeue_post_work_activity_sid - :param unicode dequeue_from: The dequeue_from - :param unicode dequeue_record: The dequeue_record - :param unicode dequeue_timeout: The dequeue_timeout - :param unicode dequeue_to: The dequeue_to - :param unicode dequeue_status_callback_url: The dequeue_status_callback_url - :param unicode call_from: The call_from - :param unicode call_record: The call_record - :param unicode call_timeout: The call_timeout - :param unicode call_to: The call_to - :param unicode call_url: The call_url - :param unicode call_status_callback_url: The call_status_callback_url - :param bool call_accept: The call_accept - :param unicode redirect_call_sid: The redirect_call_sid - :param bool redirect_accept: The redirect_accept - :param unicode redirect_url: The redirect_url - :param unicode to: The to - :param unicode from_: The from - :param unicode status_callback: The status_callback - :param unicode status_callback_method: The status_callback_method - :param ReservationInstance.CallStatus status_callback_event: The status_callback_event - :param unicode timeout: The timeout - :param bool record: The record - :param bool muted: The muted - :param unicode beep: The beep - :param bool start_conference_on_enter: The start_conference_on_enter - :param bool end_conference_on_exit: The end_conference_on_exit - :param unicode wait_url: The wait_url - :param unicode wait_method: The wait_method - :param bool early_media: The early_media - :param unicode max_participants: The max_participants - :param unicode conference_status_callback: The conference_status_callback - :param unicode conference_status_callback_method: The conference_status_callback_method - :param ReservationInstance.ConferenceEvent conference_status_callback_event: The conference_status_callback_event - :param unicode conference_record: The conference_record - :param unicode conference_trim: The conference_trim - :param unicode recording_channels: The recording_channels - :param unicode recording_status_callback: The recording_status_callback - :param unicode recording_status_callback_method: The recording_status_callback_method - :param unicode conference_recording_status_callback: The conference_recording_status_callback - :param unicode conference_recording_status_callback_method: The conference_recording_status_callback_method - :param unicode region: The region - :param unicode sip_auth_username: The sip_auth_username - :param unicode sip_auth_password: The sip_auth_password - :param unicode dequeue_status_callback_event: The dequeue_status_callback_event - :param unicode post_work_activity_sid: The post_work_activity_sid - - :returns: Updated ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationInstance + :param sid: The SID of the WorkerReservation resource to update. """ - return self._proxy.update( - 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, + return ReservationContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=sid, ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/taskrouter/v1/workspace/worker/worker_channel.py b/twilio/rest/taskrouter/v1/workspace/worker/worker_channel.py index d8d3fdda7c..6e3cc9c1dd 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/worker_channel.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/worker_channel.py @@ -1,475 +1,594 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 WorkerChannelList(ListResource): - """ """ - - def __init__(self, version, workspace_sid, worker_sid): - """ - Initialize the WorkerChannelList - - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param worker_sid: The worker_sid - - :returns: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelList - """ - super(WorkerChannelList, self).__init__(version) +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") - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'worker_sid': worker_sid, } - self._uri = '/Workspaces/{workspace_sid}/Workers/{worker_sid}/Channels'.format(**self._solution) + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + "sid": sid or self.sid, + } + self._context: Optional[WorkerChannelContext] = None - def stream(self, limit=None, page_size=None): + @property + def _proxy(self) -> "WorkerChannelContext": """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelInstance] + :returns: WorkerChannelContext for this WorkerChannelInstance """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) + 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 list(self, limit=None, page_size=None): + def fetch(self) -> "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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + Fetch the WorkerChannelInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + :returns: The fetched WorkerChannelInstance """ - Retrieve a single page of WorkerChannelInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + return self._proxy.fetch() - :returns: Page of WorkerChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelPage + async def fetch_async(self) -> "WorkerChannelInstance": """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Asynchronous coroutine to fetch the WorkerChannelInstance - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - return WorkerChannelPage(self._version, response, self._solution) - - def get_page(self, target_url): + :returns: The fetched WorkerChannelInstance """ - Retrieve a specific page of WorkerChannelInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page + return await self._proxy.fetch_async() - :returns: Page of WorkerChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelPage + def update( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> "WorkerChannelInstance": """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return WorkerChannelPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a WorkerChannelContext + Update the WorkerChannelInstance - :param sid: The sid + :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: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelContext + :returns: The updated WorkerChannelInstance """ - return WorkerChannelContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['worker_sid'], - sid=sid, + return self._proxy.update( + capacity=capacity, + available=available, ) - def __call__(self, sid): + async def update_async( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> "WorkerChannelInstance": """ - Constructs a WorkerChannelContext + Asynchronous coroutine to update the WorkerChannelInstance - :param sid: The sid + :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: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelContext + :returns: The updated WorkerChannelInstance """ - return WorkerChannelContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['worker_sid'], - sid=sid, + return await self._proxy.update_async( + capacity=capacity, + available=available, ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class WorkerChannelPage(Page): - """ """ +class WorkerChannelContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, workspace_sid: str, worker_sid: str, sid: str): """ - Initialize the WorkerChannelPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The workspace_sid - :param worker_sid: The worker_sid + Initialize the WorkerChannelContext - :returns: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelPage - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelPage + :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(WorkerChannelPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def fetch(self) -> WorkerChannelInstance: """ - Build an instance of WorkerChannelInstance + Fetch the WorkerChannelInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.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'], + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + async def fetch_async(self) -> WorkerChannelInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the WorkerChannelInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched WorkerChannelInstance """ - return '' + headers = values.of({}) -class WorkerChannelContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, workspace_sid, worker_sid, sid): - """ - Initialize the WorkerChannelContext + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param worker_sid: The worker_sid - :param sid: The sid + return WorkerChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelContext + def update( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> WorkerChannelInstance: """ - super(WorkerChannelContext, self).__init__(version) + Update the WorkerChannelInstance - # 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) + :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. - def fetch(self): + :returns: The updated WorkerChannelInstance """ - Fetch a WorkerChannelInstance - :returns: Fetched WorkerChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelInstance - """ - params = values.of({}) + 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.fetch( - 'GET', - self._uri, - params=params, + 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'], + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], ) - def update(self, capacity=values.unset, available=values.unset): + async def update_async( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> WorkerChannelInstance: """ - Update the WorkerChannelInstance + Asynchronous coroutine to update the WorkerChannelInstance - :param unicode capacity: The capacity - :param bool available: The available + :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: Updated WorkerChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelInstance + :returns: The updated WorkerChannelInstance """ - data = values.of({'Capacity': capacity, 'Available': available, }) - payload = self._version.update( - 'POST', - self._uri, - data=data, + 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'], + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class WorkerChannelInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, workspace_sid, worker_sid, sid=None): - """ - Initialize the WorkerChannelInstance - - :returns: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelInstance - """ - super(WorkerChannelInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'assigned_tasks': deserialize.integer(payload['assigned_tasks']), - 'available': payload['available'], - 'available_capacity_percentage': deserialize.integer(payload['available_capacity_percentage']), - 'configured_capacity': deserialize.integer(payload['configured_capacity']), - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'sid': payload['sid'], - 'task_channel_sid': payload['task_channel_sid'], - 'task_channel_unique_name': payload['task_channel_unique_name'], - 'worker_sid': payload['worker_sid'], - 'workspace_sid': payload['workspace_sid'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = { - 'workspace_sid': workspace_sid, - 'worker_sid': worker_sid, - 'sid': sid or self._properties['sid'], - } +class WorkerChannelPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> WorkerChannelInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of WorkerChannelInstance - :returns: WorkerChannelContext for this WorkerChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelContext + :param payload: Payload response from the API """ - 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 + return WorkerChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) - @property - def account_sid(self): + def __repr__(self) -> str: """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def assigned_tasks(self): - """ - :returns: The assigned_tasks - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['assigned_tasks'] + return "" - @property - def available(self): - """ - :returns: The available - :rtype: bool - """ - return self._properties['available'] - @property - def available_capacity_percentage(self): - """ - :returns: The available_capacity_percentage - :rtype: unicode - """ - return self._properties['available_capacity_percentage'] +class WorkerChannelList(ListResource): - @property - def configured_capacity(self): - """ - :returns: The configured_capacity - :rtype: unicode + def __init__(self, version: Version, workspace_sid: str, worker_sid: str): """ - return self._properties['configured_capacity'] + 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. - @property - def date_created(self): """ - :returns: The date_created - :rtype: datetime + 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]: """ - return self._properties['date_created'] + 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. - @property - def date_updated(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The date_updated - :rtype: datetime + 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]: """ - return self._properties['date_updated'] + 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. - @property - def sid(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The sid - :rtype: unicode + 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]: """ - return self._properties['sid'] + Lists WorkerChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def task_channel_sid(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The task_channel_sid - :rtype: unicode + 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]: """ - return self._properties['task_channel_sid'] + 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. - @property - def task_channel_unique_name(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The task_channel_unique_name - :rtype: unicode + 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: """ - return self._properties['task_channel_unique_name'] + Retrieve a single page of WorkerChannelInstance records from the API. + Request is executed immediately - @property - def worker_sid(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The worker_sid - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['worker_sid'] + Asynchronously retrieve a single page of WorkerChannelInstance records from the API. + Request is executed immediately - @property - def workspace_sid(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The workspace_sid - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['workspace_sid'] + Retrieve a specific page of WorkerChannelInstance records from the API. + Request is executed immediately - @property - def url(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of WorkerChannelInstance """ - :returns: The url - :rtype: unicode + 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: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of WorkerChannelInstance """ - Fetch a WorkerChannelInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return WorkerChannelPage(self._version, response, self._solution) - :returns: Fetched WorkerChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelInstance + def get(self, sid: str) -> WorkerChannelContext: """ - return self._proxy.fetch() + Constructs a WorkerChannelContext - def update(self, capacity=values.unset, available=values.unset): + :param sid: The SID of the WorkerChannel to update. """ - Update the WorkerChannelInstance + return WorkerChannelContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=sid, + ) - :param unicode capacity: The capacity - :param bool available: The available + def __call__(self, sid: str) -> WorkerChannelContext: + """ + Constructs a WorkerChannelContext - :returns: Updated WorkerChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelInstance + :param sid: The SID of the WorkerChannel to update. """ - return self._proxy.update(capacity=capacity, available=available, ) + return WorkerChannelContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=sid, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/taskrouter/v1/workspace/worker/worker_statistics.py b/twilio/rest/taskrouter/v1/workspace/worker/worker_statistics.py index 65f3265ede..eea670aa7d 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/worker_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/worker_statistics.py @@ -1,292 +1,292 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import serialize -from twilio.base import values +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.page import Page +from twilio.base.version import Version -class WorkerStatisticsList(ListResource): - """ """ +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 - def __init__(self, version, workspace_sid, worker_sid): + @property + def _proxy(self) -> "WorkerStatisticsContext": """ - Initialize the WorkerStatisticsList - - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param worker_sid: The worker_sid + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsList + :returns: WorkerStatisticsContext for this WorkerStatisticsInstance """ - super(WorkerStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'worker_sid': worker_sid, } + 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 get(self): + 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": """ - Constructs a WorkerStatisticsContext + 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: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsContext + :returns: The fetched WorkerStatisticsInstance """ - return WorkerStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['worker_sid'], + return self._proxy.fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, ) - def __call__(self): + 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": """ - Constructs a WorkerStatisticsContext + 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: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsContext + :returns: The fetched WorkerStatisticsInstance """ - return WorkerStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['worker_sid'], + return await self._proxy.fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class WorkerStatisticsPage(Page): - """ """ +class WorkerStatisticsContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, workspace_sid: str, worker_sid: str): """ - Initialize the WorkerStatisticsPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The workspace_sid - :param worker_sid: The worker_sid + Initialize the WorkerStatisticsContext - :returns: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsPage - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsPage + :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(WorkerStatisticsPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + } + self._uri = ( + "/Workspaces/{workspace_sid}/Workers/{worker_sid}/Statistics".format( + **self._solution + ) + ) - def get_instance(self, payload): + 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: """ - Build an instance of WorkerStatisticsInstance + Fetch the WorkerStatisticsInstance - :param dict payload: Payload response from the API + :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: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsInstance + :returns: The fetched WorkerStatisticsInstance """ - return WorkerStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['worker_sid'], + + data = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskChannel": task_channel, + } ) - def __repr__(self): - """ - Provide a friendly representation + headers = values.of({}) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Accept"] = "application/json" + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) -class WorkerStatisticsContext(InstanceContext): - """ """ + return WorkerStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) - def __init__(self, version, workspace_sid, 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: """ - Initialize the WorkerStatisticsContext + Asynchronous coroutine to fetch the WorkerStatisticsInstance - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param worker_sid: The worker_sid + :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: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsContext + :returns: The fetched WorkerStatisticsInstance """ - super(WorkerStatisticsContext, self).__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=values.unset, start_date=values.unset, - end_date=values.unset, task_channel=values.unset): - """ - Fetch a WorkerStatisticsInstance + data = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskChannel": task_channel, + } + ) - :param unicode minutes: The minutes - :param datetime start_date: The start_date - :param datetime end_date: The end_date - :param unicode task_channel: The task_channel + headers = values.of({}) - :returns: Fetched WorkerStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsInstance - """ - params = values.of({ - 'Minutes': minutes, - 'StartDate': serialize.iso8601_datetime(start_date), - 'EndDate': serialize.iso8601_datetime(end_date), - 'TaskChannel': task_channel, - }) + headers["Accept"] = "application/json" - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class WorkerStatisticsInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, workspace_sid, worker_sid): - """ - Initialize the WorkerStatisticsInstance - - :returns: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsInstance - """ - super(WorkerStatisticsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'cumulative': payload['cumulative'], - 'worker_sid': payload['worker_sid'], - 'workspace_sid': payload['workspace_sid'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'worker_sid': worker_sid, } +class WorkerStatisticsList(ListResource): - @property - def _proxy(self): + def __init__(self, version: Version, workspace_sid: str, worker_sid: str): """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Initialize the WorkerStatisticsList - :returns: WorkerStatisticsContext for this WorkerStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsContext - """ - 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 + :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. - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode """ - return self._properties['account_sid'] + super().__init__(version) - @property - def cumulative(self): - """ - :returns: The cumulative - :rtype: dict - """ - return self._properties['cumulative'] - - @property - def worker_sid(self): - """ - :returns: The worker_sid - :rtype: unicode - """ - return self._properties['worker_sid'] + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + } - @property - def workspace_sid(self): + def get(self) -> WorkerStatisticsContext: """ - :returns: The workspace_sid - :rtype: unicode - """ - return self._properties['workspace_sid'] + Constructs a WorkerStatisticsContext - @property - def url(self): """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] + return WorkerStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) - def fetch(self, minutes=values.unset, start_date=values.unset, - end_date=values.unset, task_channel=values.unset): + def __call__(self) -> WorkerStatisticsContext: """ - Fetch a WorkerStatisticsInstance - - :param unicode minutes: The minutes - :param datetime start_date: The start_date - :param datetime end_date: The end_date - :param unicode task_channel: The task_channel + Constructs a WorkerStatisticsContext - :returns: Fetched WorkerStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsInstance """ - return self._proxy.fetch( - minutes=minutes, - start_date=start_date, - end_date=end_date, - task_channel=task_channel, + return WorkerStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py b/twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py index f391cf7d9d..48a78710e2 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py @@ -1,348 +1,308 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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.page import Page - - -class WorkersCumulativeStatisticsList(ListResource): - """ """ - - def __init__(self, version, workspace_sid): - """ - Initialize the WorkersCumulativeStatisticsList - - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsList - """ - super(WorkersCumulativeStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } +from twilio.base.version import Version - def get(self): - """ - Constructs a WorkersCumulativeStatisticsContext - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsContext - """ - return WorkersCumulativeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], +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") ) - - def __call__(self): - """ - Constructs a WorkersCumulativeStatisticsContext - - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsContext - """ - return WorkersCumulativeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], + 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") - def __repr__(self): - """ - Provide a friendly representation + self._solution = { + "workspace_sid": workspace_sid, + } + self._context: Optional[WorkersCumulativeStatisticsContext] = None - :returns: Machine friendly representation - :rtype: str + @property + def _proxy(self) -> "WorkersCumulativeStatisticsContext": """ - return '' - + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context -class WorkersCumulativeStatisticsPage(Page): - """ """ + :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 __init__(self, version, response, 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": """ - Initialize the WorkersCumulativeStatisticsPage + Fetch the WorkersCumulativeStatisticsInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The workspace_sid + :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: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsPage - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsPage + :returns: The fetched WorkersCumulativeStatisticsInstance """ - super(WorkersCumulativeStatisticsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + ) - def get_instance(self, payload): + 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": """ - Build an instance of WorkersCumulativeStatisticsInstance + Asynchronous coroutine to fetch the WorkersCumulativeStatisticsInstance - :param dict payload: Payload response from the API + :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: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsInstance + :returns: The fetched WorkersCumulativeStatisticsInstance """ - return WorkersCumulativeStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], + return await self._proxy.fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) class WorkersCumulativeStatisticsContext(InstanceContext): - """ """ - def __init__(self, version, workspace_sid): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the WorkersCumulativeStatisticsContext - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsContext + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the resource to fetch. """ - super(WorkersCumulativeStatisticsContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'workspace_sid': workspace_sid, } - self._uri = '/Workspaces/{workspace_sid}/Workers/CumulativeStatistics'.format(**self._solution) + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workers/CumulativeStatistics".format( + **self._solution + ) - def fetch(self, end_date=values.unset, minutes=values.unset, - start_date=values.unset, task_channel=values.unset): + 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 a WorkersCumulativeStatisticsInstance + Fetch the WorkersCumulativeStatisticsInstance - :param datetime end_date: The end_date - :param unicode minutes: The minutes - :param datetime start_date: The start_date - :param unicode task_channel: The task_channel + :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: Fetched WorkersCumulativeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsInstance + :returns: The fetched WorkersCumulativeStatisticsInstance """ - params = values.of({ - 'EndDate': serialize.iso8601_datetime(end_date), - 'Minutes': minutes, - 'StartDate': serialize.iso8601_datetime(start_date), - 'TaskChannel': task_channel, - }) + + 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( - 'GET', - self._uri, - params=params, + method="GET", uri=self._uri, params=data, headers=headers ) return WorkersCumulativeStatisticsInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], + workspace_sid=self._solution["workspace_sid"], ) - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str + 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: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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`. -class WorkersCumulativeStatisticsInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, workspace_sid): + :returns: The fetched WorkersCumulativeStatisticsInstance """ - Initialize the WorkersCumulativeStatisticsInstance - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsInstance - """ - super(WorkersCumulativeStatisticsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'start_time': deserialize.iso8601_datetime(payload['start_time']), - 'end_time': deserialize.iso8601_datetime(payload['end_time']), - 'activity_durations': payload['activity_durations'], - 'reservations_created': deserialize.integer(payload['reservations_created']), - 'reservations_accepted': deserialize.integer(payload['reservations_accepted']), - 'reservations_rejected': deserialize.integer(payload['reservations_rejected']), - 'reservations_timed_out': deserialize.integer(payload['reservations_timed_out']), - 'reservations_canceled': deserialize.integer(payload['reservations_canceled']), - 'reservations_rescinded': deserialize.integer(payload['reservations_rescinded']), - 'workspace_sid': payload['workspace_sid'], - 'url': payload['url'], - } + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + } + ) - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, } + headers = values.of({}) - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + headers["Accept"] = "application/json" - :returns: WorkersCumulativeStatisticsContext for this WorkersCumulativeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsContext - """ - if self._context is None: - self._context = WorkersCumulativeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - ) - return self._context + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + return WorkersCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) - @property - def start_time(self): - """ - :returns: The start_time - :rtype: datetime + def __repr__(self) -> str: """ - return self._properties['start_time'] + Provide a friendly representation - @property - def end_time(self): - """ - :returns: The end_time - :rtype: datetime + :returns: Machine friendly representation """ - return self._properties['end_time'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) - @property - def activity_durations(self): - """ - :returns: The activity_durations - :rtype: dict - """ - return self._properties['activity_durations'] - @property - def reservations_created(self): - """ - :returns: The reservations_created - :rtype: unicode - """ - return self._properties['reservations_created'] - - @property - def reservations_accepted(self): - """ - :returns: The reservations_accepted - :rtype: unicode - """ - return self._properties['reservations_accepted'] +class WorkersCumulativeStatisticsList(ListResource): - @property - def reservations_rejected(self): - """ - :returns: The reservations_rejected - :rtype: unicode + def __init__(self, version: Version, workspace_sid: str): """ - return self._properties['reservations_rejected'] + Initialize the WorkersCumulativeStatisticsList - @property - def reservations_timed_out(self): - """ - :returns: The reservations_timed_out - :rtype: unicode - """ - return self._properties['reservations_timed_out'] + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the resource to fetch. - @property - def reservations_canceled(self): """ - :returns: The reservations_canceled - :rtype: unicode - """ - return self._properties['reservations_canceled'] + super().__init__(version) - @property - def reservations_rescinded(self): - """ - :returns: The reservations_rescinded - :rtype: unicode - """ - return self._properties['reservations_rescinded'] + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } - @property - def workspace_sid(self): + def get(self) -> WorkersCumulativeStatisticsContext: """ - :returns: The workspace_sid - :rtype: unicode - """ - return self._properties['workspace_sid'] + Constructs a WorkersCumulativeStatisticsContext - @property - def url(self): - """ - :returns: The url - :rtype: unicode """ - return self._properties['url'] + return WorkersCumulativeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) - def fetch(self, end_date=values.unset, minutes=values.unset, - start_date=values.unset, task_channel=values.unset): + def __call__(self) -> WorkersCumulativeStatisticsContext: """ - Fetch a WorkersCumulativeStatisticsInstance - - :param datetime end_date: The end_date - :param unicode minutes: The minutes - :param datetime start_date: The start_date - :param unicode task_channel: The task_channel + Constructs a WorkersCumulativeStatisticsContext - :returns: Fetched WorkersCumulativeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsInstance """ - return self._proxy.fetch( - end_date=end_date, - minutes=minutes, - start_date=start_date, - task_channel=task_channel, + return WorkersCumulativeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 index 9d6f36a660..2e9970478e 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/workers_real_time_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/workers_real_time_statistics.py @@ -1,266 +1,239 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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.page import Page - +from twilio.base.version import Version -class WorkersRealTimeStatisticsList(ListResource): - """ """ - def __init__(self, version, workspace_sid): - """ - Initialize the WorkersRealTimeStatisticsList +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") - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid + self._solution = { + "workspace_sid": workspace_sid, + } + self._context: Optional[WorkersRealTimeStatisticsContext] = None - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsList + @property + def _proxy(self) -> "WorkersRealTimeStatisticsContext": """ - super(WorkersRealTimeStatisticsList, self).__init__(version) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } + :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 get(self): + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> "WorkersRealTimeStatisticsInstance": """ - Constructs a WorkersRealTimeStatisticsContext + 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: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsContext + :returns: The fetched WorkersRealTimeStatisticsInstance """ - return WorkersRealTimeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], + return self._proxy.fetch( + task_channel=task_channel, ) - def __call__(self): + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> "WorkersRealTimeStatisticsInstance": """ - Constructs a WorkersRealTimeStatisticsContext + Asynchronous coroutine to fetch the WorkersRealTimeStatisticsInstance - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsContext + :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 WorkersRealTimeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], + return await self._proxy.fetch_async( + task_channel=task_channel, ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) -class WorkersRealTimeStatisticsPage(Page): - """ """ +class WorkersRealTimeStatisticsContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, workspace_sid: str): """ - Initialize the WorkersRealTimeStatisticsPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The workspace_sid + Initialize the WorkersRealTimeStatisticsContext - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsPage - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsPage + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the resource to fetch. """ - super(WorkersRealTimeStatisticsPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workers/RealTimeStatistics".format( + **self._solution + ) - def get_instance(self, payload): + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> WorkersRealTimeStatisticsInstance: """ - Build an instance of WorkersRealTimeStatisticsInstance + Fetch the WorkersRealTimeStatisticsInstance - :param dict payload: Payload response from the API + :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: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsInstance + :returns: The fetched WorkersRealTimeStatisticsInstance """ - return WorkersRealTimeStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], + + data = values.of( + { + "TaskChannel": task_channel, + } ) - def __repr__(self): - """ - Provide a friendly representation + headers = values.of({}) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Accept"] = "application/json" + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) -class WorkersRealTimeStatisticsContext(InstanceContext): - """ """ + return WorkersRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) - def __init__(self, version, workspace_sid): + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> WorkersRealTimeStatisticsInstance: """ - Initialize the WorkersRealTimeStatisticsContext + Asynchronous coroutine to fetch the WorkersRealTimeStatisticsInstance - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid + :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: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsContext + :returns: The fetched WorkersRealTimeStatisticsInstance """ - super(WorkersRealTimeStatisticsContext, self).__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=values.unset): - """ - Fetch a WorkersRealTimeStatisticsInstance + data = values.of( + { + "TaskChannel": task_channel, + } + ) - :param unicode task_channel: The task_channel + headers = values.of({}) - :returns: Fetched WorkersRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsInstance - """ - params = values.of({'TaskChannel': task_channel, }) + headers["Accept"] = "application/json" - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + workspace_sid=self._solution["workspace_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class WorkersRealTimeStatisticsInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, workspace_sid): """ - Initialize the WorkersRealTimeStatisticsInstance - - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsInstance - """ - super(WorkersRealTimeStatisticsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'activity_statistics': payload['activity_statistics'], - 'total_workers': deserialize.integer(payload['total_workers']), - 'workspace_sid': payload['workspace_sid'], - 'url': payload['url'], - } + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, } - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context +class WorkersRealTimeStatisticsList(ListResource): - :returns: WorkersRealTimeStatisticsContext for this WorkersRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsContext + def __init__(self, version: Version, workspace_sid: str): """ - if self._context is None: - self._context = WorkersRealTimeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - ) - return self._context + Initialize the WorkersRealTimeStatisticsList - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the resource to fetch. - @property - def activity_statistics(self): - """ - :returns: The activity_statistics - :rtype: dict """ - return self._properties['activity_statistics'] + super().__init__(version) - @property - def total_workers(self): - """ - :returns: The total_workers - :rtype: unicode - """ - return self._properties['total_workers'] + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } - @property - def workspace_sid(self): - """ - :returns: The workspace_sid - :rtype: unicode + def get(self) -> WorkersRealTimeStatisticsContext: """ - return self._properties['workspace_sid'] + Constructs a WorkersRealTimeStatisticsContext - @property - def url(self): - """ - :returns: The url - :rtype: unicode """ - return self._properties['url'] + return WorkersRealTimeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) - def fetch(self, task_channel=values.unset): + def __call__(self) -> WorkersRealTimeStatisticsContext: """ - Fetch a WorkersRealTimeStatisticsInstance - - :param unicode task_channel: The task_channel + Constructs a WorkersRealTimeStatisticsContext - :returns: Fetched WorkersRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsInstance """ - return self._proxy.fetch(task_channel=task_channel, ) + return WorkersRealTimeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py b/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py index bef1b08151..31c79ee6ba 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py @@ -1,294 +1,308 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import serialize -from twilio.base import values +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.page import Page - - -class WorkersStatisticsList(ListResource): - """ """ +from twilio.base.version import Version - def __init__(self, version, workspace_sid): - """ - Initialize the WorkersStatisticsList - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsList - """ - super(WorkersStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } +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 - def get(self): + @property + def _proxy(self) -> "WorkersStatisticsContext": """ - Constructs a 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: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsContext + :returns: WorkersStatisticsContext for this WorkersStatisticsInstance """ - return WorkersStatisticsContext(self._version, workspace_sid=self._solution['workspace_sid'], ) + if self._context is None: + self._context = WorkersStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + ) + return self._context - def __call__(self): + 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 """ - Constructs a WorkersStatisticsContext + 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, + ) - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsContext - """ - return WorkersStatisticsContext(self._version, 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 + """ + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class WorkersStatisticsPage(Page): - """ """ +class WorkersStatisticsContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, workspace_sid: str): """ - Initialize the WorkersStatisticsPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The workspace_sid + Initialize the WorkersStatisticsContext - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsPage - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsPage + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Worker to fetch. """ - super(WorkersStatisticsPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workers/Statistics".format( + **self._solution + ) - def get_instance(self, payload): - """ - Build an instance of WorkersStatisticsInstance + 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, + } + ) - :param dict payload: Payload response from the API + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsInstance - """ return WorkersStatisticsInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], + workspace_sid=self._solution["workspace_sid"], ) - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class WorkersStatisticsContext(InstanceContext): - """ """ - - def __init__(self, version, workspace_sid): - """ - Initialize the WorkersStatisticsContext - - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsContext - """ - super(WorkersStatisticsContext, self).__init__(version) + 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, + } + ) - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } - self._uri = '/Workspaces/{workspace_sid}/Workers/Statistics'.format(**self._solution) + headers = values.of({}) - def fetch(self, minutes=values.unset, start_date=values.unset, - end_date=values.unset, task_queue_sid=values.unset, - task_queue_name=values.unset, friendly_name=values.unset, - task_channel=values.unset): - """ - Fetch a WorkersStatisticsInstance - - :param unicode minutes: The minutes - :param datetime start_date: The start_date - :param datetime end_date: The end_date - :param unicode task_queue_sid: The task_queue_sid - :param unicode task_queue_name: The task_queue_name - :param unicode friendly_name: The friendly_name - :param unicode task_channel: The task_channel - - :returns: Fetched WorkersStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsInstance - """ - params = 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["Accept"] = "application/json" - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + workspace_sid=self._solution["workspace_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class WorkersStatisticsInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, workspace_sid): - """ - Initialize the WorkersStatisticsInstance +class WorkersStatisticsList(ListResource): - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsInstance + def __init__(self, version: Version, workspace_sid: str): """ - super(WorkersStatisticsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'realtime': payload['realtime'], - 'cumulative': payload['cumulative'], - 'account_sid': payload['account_sid'], - 'workspace_sid': payload['workspace_sid'], - 'url': payload['url'], - } + Initialize the WorkersStatisticsList - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, } + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Worker to fetch. - @property - def _proxy(self): """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + super().__init__(version) - :returns: WorkersStatisticsContext for this WorkersStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsContext - """ - if self._context is None: - self._context = WorkersStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - ) - return self._context - - @property - def realtime(self): - """ - :returns: The realtime - :rtype: dict - """ - return self._properties['realtime'] - - @property - def cumulative(self): - """ - :returns: The cumulative - :rtype: dict - """ - return self._properties['cumulative'] + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } - @property - def account_sid(self): + def get(self) -> WorkersStatisticsContext: """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + Constructs a WorkersStatisticsContext - @property - def workspace_sid(self): """ - :returns: The workspace_sid - :rtype: unicode - """ - return self._properties['workspace_sid'] + return WorkersStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) - @property - def url(self): - """ - :returns: The url - :rtype: unicode + def __call__(self) -> WorkersStatisticsContext: """ - return self._properties['url'] + Constructs a WorkersStatisticsContext - def fetch(self, minutes=values.unset, start_date=values.unset, - end_date=values.unset, task_queue_sid=values.unset, - task_queue_name=values.unset, friendly_name=values.unset, - task_channel=values.unset): - """ - Fetch a WorkersStatisticsInstance - - :param unicode minutes: The minutes - :param datetime start_date: The start_date - :param datetime end_date: The end_date - :param unicode task_queue_sid: The task_queue_sid - :param unicode task_queue_name: The task_queue_name - :param unicode friendly_name: The friendly_name - :param unicode task_channel: The task_channel - - :returns: Fetched WorkersStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.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, + return WorkersStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py b/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py index cb78bbe730..619ae1bce9 100644 --- a/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py @@ -1,618 +1,837 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 +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 WorkflowList(ListResource): - """ """ +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 - def __init__(self, version, workspace_sid): + @property + def _proxy(self) -> "WorkflowContext": """ - Initialize the WorkflowList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid + :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 - :returns: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowList - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowList + def delete(self) -> bool: """ - super(WorkflowList, self).__init__(version) + Deletes the WorkflowInstance - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } - self._uri = '/Workspaces/{workspace_sid}/Workflows'.format(**self._solution) - def stream(self, friendly_name=values.unset, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 unicode friendly_name: The friendly_name - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.workflow.WorkflowInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the WorkflowInstance - page = self.page(friendly_name=friendly_name, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, friendly_name=values.unset, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the WorkflowInstance - :param unicode friendly_name: The friendly_name - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.workflow.WorkflowInstance] + :returns: The fetched WorkflowInstance """ - return list(self.stream(friendly_name=friendly_name, limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, friendly_name=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + async def fetch_async(self) -> "WorkflowInstance": """ - Retrieve a single page of WorkflowInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the WorkflowInstance - :param unicode friendly_name: The friendly_name - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of WorkflowInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowPage + :returns: The fetched WorkflowInstance """ - params = values.of({ - 'FriendlyName': friendly_name, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return WorkflowPage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def get_page(self, target_url): + 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": """ - Retrieve a specific page of WorkflowInstance records from the API. - Request is executed immediately + Update the WorkflowInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of WorkflowInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowPage + :returns: The updated WorkflowInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, ) - return WorkflowPage(self._version, response, self._solution) - - def create(self, friendly_name, configuration, - assignment_callback_url=values.unset, - fallback_assignment_callback_url=values.unset, - task_reservation_timeout=values.unset): + 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": """ - Create a new WorkflowInstance + Asynchronous coroutine to update the WorkflowInstance - :param unicode friendly_name: The friendly_name - :param unicode configuration: The configuration - :param unicode assignment_callback_url: The assignment_callback_url - :param unicode fallback_assignment_callback_url: The fallback_assignment_callback_url - :param unicode task_reservation_timeout: The task_reservation_timeout + :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: Newly created WorkflowInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowInstance + :returns: The updated WorkflowInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Configuration': configuration, - 'AssignmentCallbackUrl': assignment_callback_url, - 'FallbackAssignmentCallbackUrl': fallback_assignment_callback_url, - 'TaskReservationTimeout': task_reservation_timeout, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, + 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, ) - return WorkflowInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) - - def get(self, sid): + @property + def cumulative_statistics(self) -> WorkflowCumulativeStatisticsList: """ - Constructs a WorkflowContext - - :param sid: The sid - - :returns: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowContext - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowContext + Access the cumulative_statistics """ - return WorkflowContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + return self._proxy.cumulative_statistics - def __call__(self, sid): + @property + def real_time_statistics(self) -> WorkflowRealTimeStatisticsList: """ - Constructs a WorkflowContext - - :param sid: The sid + Access the real_time_statistics + """ + return self._proxy.real_time_statistics - :returns: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowContext - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowContext + @property + def statistics(self) -> WorkflowStatisticsList: + """ + Access the statistics """ - return WorkflowContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + return self._proxy.statistics - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class WorkflowPage(Page): - """ """ +class WorkflowContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, workspace_sid: str, sid: str): """ - Initialize the WorkflowPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The workspace_sid + Initialize the WorkflowContext - :returns: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowPage - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowPage + :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(WorkflowPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workflows/{sid}".format( + **self._solution + ) - def get_instance(self, payload): + self._cumulative_statistics: Optional[WorkflowCumulativeStatisticsList] = None + self._real_time_statistics: Optional[WorkflowRealTimeStatisticsList] = None + self._statistics: Optional[WorkflowStatisticsList] = None + + def delete(self) -> bool: """ - Build an instance of WorkflowInstance + Deletes the WorkflowInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowInstance + :returns: True if delete succeeds, False otherwise """ - return WorkflowInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the WorkflowInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class WorkflowContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, workspace_sid, sid): + def fetch(self) -> WorkflowInstance: """ - Initialize the WorkflowContext + Fetch the WorkflowInstance - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param sid: The sid - :returns: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowContext - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowContext + :returns: The fetched WorkflowInstance """ - super(WorkflowContext, self).__init__(version) - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'sid': sid, } - self._uri = '/Workspaces/{workspace_sid}/Workflows/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - # Dependents - self._statistics = None - self._real_time_statistics = None - self._cumulative_statistics = None + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return WorkflowInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> WorkflowInstance: """ - Fetch a WorkflowInstance + Asynchronous coroutine to fetch the WorkflowInstance - :returns: Fetched WorkflowInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowInstance + + :returns: The fetched WorkflowInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - def update(self, friendly_name=values.unset, - assignment_callback_url=values.unset, - fallback_assignment_callback_url=values.unset, - configuration=values.unset, task_reservation_timeout=values.unset): + 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 unicode friendly_name: The friendly_name - :param unicode assignment_callback_url: The assignment_callback_url - :param unicode fallback_assignment_callback_url: The fallback_assignment_callback_url - :param unicode configuration: The configuration - :param unicode task_reservation_timeout: The task_reservation_timeout + :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({}) - :returns: Updated WorkflowInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'AssignmentCallbackUrl': assignment_callback_url, - 'FallbackAssignmentCallbackUrl': fallback_assignment_callback_url, - 'Configuration': configuration, - 'TaskReservationTimeout': task_reservation_timeout, - }) + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" payload = self._version.update( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) return WorkflowInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - def delete(self): - """ - Deletes the WorkflowInstance + 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({}) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + 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 statistics(self): + def cumulative_statistics(self) -> WorkflowCumulativeStatisticsList: """ - Access the statistics - - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsList + Access the cumulative_statistics """ - if self._statistics is None: - self._statistics = WorkflowStatisticsList( + if self._cumulative_statistics is None: + self._cumulative_statistics = WorkflowCumulativeStatisticsList( self._version, - workspace_sid=self._solution['workspace_sid'], - workflow_sid=self._solution['sid'], + self._solution["workspace_sid"], + self._solution["sid"], ) - return self._statistics + return self._cumulative_statistics @property - def real_time_statistics(self): + def real_time_statistics(self) -> WorkflowRealTimeStatisticsList: """ Access the real_time_statistics - - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsList """ if self._real_time_statistics is None: self._real_time_statistics = WorkflowRealTimeStatisticsList( self._version, - workspace_sid=self._solution['workspace_sid'], - workflow_sid=self._solution['sid'], + self._solution["workspace_sid"], + self._solution["sid"], ) return self._real_time_statistics @property - def cumulative_statistics(self): + def statistics(self) -> WorkflowStatisticsList: """ - Access the cumulative_statistics - - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsList + Access the statistics """ - if self._cumulative_statistics is None: - self._cumulative_statistics = WorkflowCumulativeStatisticsList( + if self._statistics is None: + self._statistics = WorkflowStatisticsList( self._version, - workspace_sid=self._solution['workspace_sid'], - workflow_sid=self._solution['sid'], + self._solution["workspace_sid"], + self._solution["sid"], ) - return self._cumulative_statistics + return self._statistics - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class WorkflowInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, workspace_sid, sid=None): - """ - Initialize the WorkflowInstance - - :returns: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowInstance - """ - super(WorkflowInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'assignment_callback_url': payload['assignment_callback_url'], - 'configuration': payload['configuration'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'document_content_type': payload['document_content_type'], - 'fallback_assignment_callback_url': payload['fallback_assignment_callback_url'], - 'friendly_name': payload['friendly_name'], - 'sid': payload['sid'], - 'task_reservation_timeout': deserialize.integer(payload['task_reservation_timeout']), - 'workspace_sid': payload['workspace_sid'], - 'url': payload['url'], - 'links': payload['links'], - } - - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'sid': sid or self._properties['sid'], } +class WorkflowPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> WorkflowInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of WorkflowInstance - :returns: WorkflowContext for this WorkflowInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = WorkflowContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], - ) - return self._context + return WorkflowInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def assignment_callback_url(self): - """ - :returns: The assignment_callback_url - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['assignment_callback_url'] + return "" - @property - def configuration(self): - """ - :returns: The configuration - :rtype: unicode - """ - return self._properties['configuration'] - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] +class WorkflowList(ListResource): - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime + def __init__(self, version: Version, workspace_sid: str): """ - return self._properties['date_updated'] + Initialize the WorkflowList - @property - def document_content_type(self): - """ - :returns: The document_content_type - :rtype: unicode - """ - return self._properties['document_content_type'] + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Workflow to read. - @property - def fallback_assignment_callback_url(self): """ - :returns: The fallback_assignment_callback_url - :rtype: unicode - """ - return self._properties['fallback_assignment_callback_url'] + super().__init__(version) - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] + # 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"}) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def task_reservation_timeout(self): - """ - :returns: The task_reservation_timeout - :rtype: unicode - """ - return self._properties['task_reservation_timeout'] + headers["Accept"] = "application/json" - @property - def workspace_sid(self): + 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]: """ - :returns: The workspace_sid - :rtype: unicode + 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 """ - return self._properties['workspace_sid'] + limits = self._version.read_limits(limit, page_size) + page = self.page(friendly_name=friendly_name, page_size=limits["page_size"]) - @property - def url(self): + 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]: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) - @property - def links(self): + 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]: """ - :returns: The links - :rtype: unicode + 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]: """ - return self._properties['links'] + 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 fetch(self): + 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: """ - Fetch a WorkflowInstance + Retrieve a single page of WorkflowInstance records from the API. + Request is executed immediately - :returns: Fetched WorkflowInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowInstance + :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 """ - return self._proxy.fetch() + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - def update(self, friendly_name=values.unset, - assignment_callback_url=values.unset, - fallback_assignment_callback_url=values.unset, - configuration=values.unset, task_reservation_timeout=values.unset): + headers = values.of({"Content-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: """ - Update the WorkflowInstance + Asynchronously retrieve a single page of WorkflowInstance records from the API. + Request is executed immediately - :param unicode friendly_name: The friendly_name - :param unicode assignment_callback_url: The assignment_callback_url - :param unicode fallback_assignment_callback_url: The fallback_assignment_callback_url - :param unicode configuration: The configuration - :param unicode task_reservation_timeout: The task_reservation_timeout + :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: Updated WorkflowInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowInstance + :returns: Page of 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, + 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 delete(self): + def get_page(self, target_url: str) -> WorkflowPage: """ - Deletes the WorkflowInstance + Retrieve a specific page of WorkflowInstance records from the API. + Request is executed immediately - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param target_url: API-generated URL for the requested results page + + :returns: Page of WorkflowInstance """ - return self._proxy.delete() + response = self._version.domain.twilio.request("GET", target_url) + return WorkflowPage(self._version, response, self._solution) - @property - def statistics(self): + async def get_page_async(self, target_url: str) -> WorkflowPage: """ - Access the statistics + 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: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsList + :returns: Page of WorkflowInstance """ - return self._proxy.statistics + response = await self._version.domain.twilio.request_async("GET", target_url) + return WorkflowPage(self._version, response, self._solution) - @property - def real_time_statistics(self): + def get(self, sid: str) -> WorkflowContext: """ - Access the real_time_statistics + Constructs a WorkflowContext - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsList + :param sid: The SID of the Workflow resource to update. """ - return self._proxy.real_time_statistics + return WorkflowContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) - @property - def cumulative_statistics(self): + def __call__(self, sid: str) -> WorkflowContext: """ - Access the cumulative_statistics + Constructs a WorkflowContext - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsList + :param sid: The SID of the Workflow resource to update. """ - return self._proxy.cumulative_statistics + return WorkflowContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/taskrouter/v1/workspace/workflow/workflow_cumulative_statistics.py b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_cumulative_statistics.py index c8a7fda5a8..d6d7c094cc 100644 --- a/twilio/rest/taskrouter/v1/workspace/workflow/workflow_cumulative_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_cumulative_statistics.py @@ -1,452 +1,376 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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.page import Page - - -class WorkflowCumulativeStatisticsList(ListResource): - """ """ - - def __init__(self, version, workspace_sid, workflow_sid): - """ - Initialize the WorkflowCumulativeStatisticsList +from twilio.base.version import Version - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param workflow_sid: The workflow_sid - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsList - """ - super(WorkflowCumulativeStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'workflow_sid': workflow_sid, } - - def get(self): - """ - Constructs a WorkflowCumulativeStatisticsContext - - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsContext - """ - return WorkflowCumulativeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - workflow_sid=self._solution['workflow_sid'], +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") ) - - def __call__(self): - """ - Constructs a WorkflowCumulativeStatisticsContext - - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsContext - """ - return WorkflowCumulativeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - workflow_sid=self._solution['workflow_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.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") - def __repr__(self): - """ - Provide a friendly representation + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } + self._context: Optional[WorkflowCumulativeStatisticsContext] = None - :returns: Machine friendly representation - :rtype: str + @property + def _proxy(self) -> "WorkflowCumulativeStatisticsContext": """ - return '' - + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context -class WorkflowCumulativeStatisticsPage(Page): - """ """ + :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 __init__(self, version, response, 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": """ - Initialize the WorkflowCumulativeStatisticsPage + Fetch the WorkflowCumulativeStatisticsInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The workspace_sid - :param workflow_sid: The workflow_sid + :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: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsPage - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsPage + :returns: The fetched WorkflowCumulativeStatisticsInstance """ - super(WorkflowCumulativeStatisticsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + 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, + ) - def get_instance(self, payload): + 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": """ - Build an instance of WorkflowCumulativeStatisticsInstance + Asynchronous coroutine to fetch the WorkflowCumulativeStatisticsInstance - :param dict payload: Payload response from the API + :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: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsInstance + :returns: The fetched WorkflowCumulativeStatisticsInstance """ - return WorkflowCumulativeStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - workflow_sid=self._solution['workflow_sid'], + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) class WorkflowCumulativeStatisticsContext(InstanceContext): - """ """ - def __init__(self, version, workspace_sid, workflow_sid): + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): """ Initialize the WorkflowCumulativeStatisticsContext - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param workflow_sid: The workflow_sid - - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.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(WorkflowCumulativeStatisticsContext, self).__init__(version) + 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) + 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=values.unset, minutes=values.unset, - start_date=values.unset, task_channel=values.unset, - split_by_wait_time=values.unset): - """ - Fetch a WorkflowCumulativeStatisticsInstance + 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, + } + ) - :param datetime end_date: The end_date - :param unicode minutes: The minutes - :param datetime start_date: The start_date - :param unicode task_channel: The task_channel - :param unicode split_by_wait_time: The split_by_wait_time + headers = values.of({}) - :returns: Fetched WorkflowCumulativeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsInstance - """ - params = 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["Accept"] = "application/json" payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], ) - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class WorkflowCumulativeStatisticsInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, workspace_sid, workflow_sid): - """ - Initialize the WorkflowCumulativeStatisticsInstance - - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsInstance - """ - super(WorkflowCumulativeStatisticsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'avg_task_acceptance_time': deserialize.integer(payload['avg_task_acceptance_time']), - 'start_time': deserialize.iso8601_datetime(payload['start_time']), - 'end_time': deserialize.iso8601_datetime(payload['end_time']), - 'reservations_created': deserialize.integer(payload['reservations_created']), - 'reservations_accepted': deserialize.integer(payload['reservations_accepted']), - 'reservations_rejected': deserialize.integer(payload['reservations_rejected']), - 'reservations_timed_out': deserialize.integer(payload['reservations_timed_out']), - 'reservations_canceled': deserialize.integer(payload['reservations_canceled']), - 'reservations_rescinded': deserialize.integer(payload['reservations_rescinded']), - 'split_by_wait_time': payload['split_by_wait_time'], - 'wait_duration_until_accepted': payload['wait_duration_until_accepted'], - 'wait_duration_until_canceled': payload['wait_duration_until_canceled'], - 'tasks_canceled': deserialize.integer(payload['tasks_canceled']), - 'tasks_completed': deserialize.integer(payload['tasks_completed']), - 'tasks_entered': deserialize.integer(payload['tasks_entered']), - 'tasks_deleted': deserialize.integer(payload['tasks_deleted']), - 'tasks_moved': deserialize.integer(payload['tasks_moved']), - 'tasks_timed_out_in_workflow': deserialize.integer(payload['tasks_timed_out_in_workflow']), - 'workflow_sid': payload['workflow_sid'], - 'workspace_sid': payload['workspace_sid'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'workflow_sid': workflow_sid, } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsContext - """ - 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 - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def avg_task_acceptance_time(self): - """ - :returns: The avg_task_acceptance_time - :rtype: unicode - """ - return self._properties['avg_task_acceptance_time'] - - @property - def start_time(self): - """ - :returns: The start_time - :rtype: datetime - """ - return self._properties['start_time'] - - @property - def end_time(self): - """ - :returns: The end_time - :rtype: datetime - """ - return self._properties['end_time'] - - @property - def reservations_created(self): - """ - :returns: The reservations_created - :rtype: unicode - """ - return self._properties['reservations_created'] - - @property - def reservations_accepted(self): - """ - :returns: The reservations_accepted - :rtype: unicode - """ - return self._properties['reservations_accepted'] + 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, + } + ) - @property - def reservations_rejected(self): - """ - :returns: The reservations_rejected - :rtype: unicode - """ - return self._properties['reservations_rejected'] + headers = values.of({}) - @property - def reservations_timed_out(self): - """ - :returns: The reservations_timed_out - :rtype: unicode - """ - return self._properties['reservations_timed_out'] + headers["Accept"] = "application/json" - @property - def reservations_canceled(self): - """ - :returns: The reservations_canceled - :rtype: unicode - """ - return self._properties['reservations_canceled'] - - @property - def reservations_rescinded(self): - """ - :returns: The reservations_rescinded - :rtype: unicode - """ - return self._properties['reservations_rescinded'] - - @property - def split_by_wait_time(self): - """ - :returns: The split_by_wait_time - :rtype: dict - """ - return self._properties['split_by_wait_time'] + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) - @property - def wait_duration_until_accepted(self): - """ - :returns: The wait_duration_until_accepted - :rtype: dict - """ - return self._properties['wait_duration_until_accepted'] + return WorkflowCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) - @property - def wait_duration_until_canceled(self): - """ - :returns: The wait_duration_until_canceled - :rtype: dict + def __repr__(self) -> str: """ - return self._properties['wait_duration_until_canceled'] + Provide a friendly representation - @property - def tasks_canceled(self): - """ - :returns: The tasks_canceled - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['tasks_canceled'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) - @property - def tasks_completed(self): - """ - :returns: The tasks_completed - :rtype: unicode - """ - return self._properties['tasks_completed'] - @property - def tasks_entered(self): - """ - :returns: The tasks_entered - :rtype: unicode - """ - return self._properties['tasks_entered'] +class WorkflowCumulativeStatisticsList(ListResource): - @property - def tasks_deleted(self): - """ - :returns: The tasks_deleted - :rtype: unicode + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): """ - return self._properties['tasks_deleted'] + Initialize the WorkflowCumulativeStatisticsList - @property - def tasks_moved(self): - """ - :returns: The tasks_moved - :rtype: unicode - """ - return self._properties['tasks_moved'] + :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. - @property - def tasks_timed_out_in_workflow(self): - """ - :returns: The tasks_timed_out_in_workflow - :rtype: unicode """ - return self._properties['tasks_timed_out_in_workflow'] + super().__init__(version) - @property - def workflow_sid(self): - """ - :returns: The workflow_sid - :rtype: unicode - """ - return self._properties['workflow_sid'] + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } - @property - def workspace_sid(self): - """ - :returns: The workspace_sid - :rtype: unicode + def get(self) -> WorkflowCumulativeStatisticsContext: """ - return self._properties['workspace_sid'] + Constructs a WorkflowCumulativeStatisticsContext - @property - def url(self): - """ - :returns: The url - :rtype: unicode """ - return self._properties['url'] + return WorkflowCumulativeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) - def fetch(self, end_date=values.unset, minutes=values.unset, - start_date=values.unset, task_channel=values.unset, - split_by_wait_time=values.unset): + def __call__(self) -> WorkflowCumulativeStatisticsContext: """ - Fetch a WorkflowCumulativeStatisticsInstance - - :param datetime end_date: The end_date - :param unicode minutes: The minutes - :param datetime start_date: The start_date - :param unicode task_channel: The task_channel - :param unicode split_by_wait_time: The split_by_wait_time + Constructs a WorkflowCumulativeStatisticsContext - :returns: Fetched WorkflowCumulativeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.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, + return WorkflowCumulativeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 index a83bc0e30e..9387622518 100644 --- a/twilio/rest/taskrouter/v1/workspace/workflow/workflow_real_time_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_real_time_statistics.py @@ -1,301 +1,271 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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.page import Page - - -class WorkflowRealTimeStatisticsList(ListResource): - """ """ +from twilio.base.version import Version - def __init__(self, version, workspace_sid, workflow_sid): - """ - Initialize the WorkflowRealTimeStatisticsList - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param workflow_sid: The workflow_sid - - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsList - """ - super(WorkflowRealTimeStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'workflow_sid': workflow_sid, } - - def get(self): - """ - Constructs a WorkflowRealTimeStatisticsContext - - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsContext - """ - return WorkflowRealTimeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - workflow_sid=self._solution['workflow_sid'], +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") ) - - def __call__(self): - """ - Constructs a WorkflowRealTimeStatisticsContext - - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsContext - """ - return WorkflowRealTimeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - workflow_sid=self._solution['workflow_sid'], + 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") - def __repr__(self): - """ - Provide a friendly representation + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } + self._context: Optional[WorkflowRealTimeStatisticsContext] = None - :returns: Machine friendly representation - :rtype: str + @property + def _proxy(self) -> "WorkflowRealTimeStatisticsContext": """ - return '' - + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context -class WorkflowRealTimeStatisticsPage(Page): - """ """ + :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 __init__(self, version, response, solution): + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> "WorkflowRealTimeStatisticsInstance": """ - Initialize the WorkflowRealTimeStatisticsPage + Fetch the WorkflowRealTimeStatisticsInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The workspace_sid - :param workflow_sid: The workflow_sid + :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: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsPage - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsPage + :returns: The fetched WorkflowRealTimeStatisticsInstance """ - super(WorkflowRealTimeStatisticsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch( + task_channel=task_channel, + ) - def get_instance(self, payload): + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> "WorkflowRealTimeStatisticsInstance": """ - Build an instance of WorkflowRealTimeStatisticsInstance + Asynchronous coroutine to fetch the WorkflowRealTimeStatisticsInstance - :param dict payload: Payload response from the API + :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: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsInstance + :returns: The fetched WorkflowRealTimeStatisticsInstance """ - return WorkflowRealTimeStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - workflow_sid=self._solution['workflow_sid'], + return await self._proxy.fetch_async( + task_channel=task_channel, ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) class WorkflowRealTimeStatisticsContext(InstanceContext): - """ """ - def __init__(self, version, workspace_sid, workflow_sid): + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): """ Initialize the WorkflowRealTimeStatisticsContext - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param workflow_sid: The workflow_sid - - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.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(WorkflowRealTimeStatisticsContext, self).__init__(version) + 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) + 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=values.unset): + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> WorkflowRealTimeStatisticsInstance: """ - Fetch a WorkflowRealTimeStatisticsInstance + Fetch the WorkflowRealTimeStatisticsInstance - :param unicode task_channel: The task_channel + :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: Fetched WorkflowRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsInstance + :returns: The fetched WorkflowRealTimeStatisticsInstance """ - params = values.of({'TaskChannel': task_channel, }) + + data = values.of( + { + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], ) - def __repr__(self): + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> WorkflowRealTimeStatisticsInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the WorkflowRealTimeStatisticsInstance - :returns: Machine friendly representation - :rtype: str + :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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + data = values.of( + { + "TaskChannel": task_channel, + } + ) -class WorkflowRealTimeStatisticsInstance(InstanceResource): - """ """ + headers = values.of({}) - def __init__(self, version, payload, workspace_sid, workflow_sid): - """ - Initialize the WorkflowRealTimeStatisticsInstance + headers["Accept"] = "application/json" - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsInstance - """ - super(WorkflowRealTimeStatisticsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'longest_task_waiting_age': deserialize.integer(payload['longest_task_waiting_age']), - 'tasks_by_priority': payload['tasks_by_priority'], - 'tasks_by_status': payload['tasks_by_status'], - 'total_tasks': deserialize.integer(payload['total_tasks']), - 'workflow_sid': payload['workflow_sid'], - 'workspace_sid': payload['workspace_sid'], - 'url': payload['url'], - } + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'workflow_sid': workflow_sid, } + return WorkflowRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) - @property - def _proxy(self): + def __repr__(self) -> str: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Provide a friendly representation - :returns: WorkflowRealTimeStatisticsContext for this WorkflowRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsContext + :returns: Machine friendly representation """ - 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 + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def longest_task_waiting_age(self): - """ - :returns: The longest_task_waiting_age - :rtype: unicode - """ - return self._properties['longest_task_waiting_age'] +class WorkflowRealTimeStatisticsList(ListResource): - @property - def tasks_by_priority(self): - """ - :returns: The tasks_by_priority - :rtype: dict + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): """ - return self._properties['tasks_by_priority'] + Initialize the WorkflowRealTimeStatisticsList - @property - def tasks_by_status(self): - """ - :returns: The tasks_by_status - :rtype: dict - """ - return self._properties['tasks_by_status'] + :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. - @property - def total_tasks(self): """ - :returns: The total_tasks - :rtype: unicode - """ - return self._properties['total_tasks'] + super().__init__(version) - @property - def workflow_sid(self): - """ - :returns: The workflow_sid - :rtype: unicode - """ - return self._properties['workflow_sid'] + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } - @property - def workspace_sid(self): + def get(self) -> WorkflowRealTimeStatisticsContext: """ - :returns: The workspace_sid - :rtype: unicode - """ - return self._properties['workspace_sid'] + Constructs a WorkflowRealTimeStatisticsContext - @property - def url(self): - """ - :returns: The url - :rtype: unicode """ - return self._properties['url'] + return WorkflowRealTimeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) - def fetch(self, task_channel=values.unset): + def __call__(self) -> WorkflowRealTimeStatisticsContext: """ - Fetch a WorkflowRealTimeStatisticsInstance - - :param unicode task_channel: The task_channel + Constructs a WorkflowRealTimeStatisticsContext - :returns: Fetched WorkflowRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsInstance """ - return self._proxy.fetch(task_channel=task_channel, ) + return WorkflowRealTimeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py index b52555d504..e49bd32d6e 100644 --- a/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py @@ -1,307 +1,306 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import serialize -from twilio.base import values +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.page import Page - - -class WorkflowStatisticsList(ListResource): - """ """ +from twilio.base.version import Version - def __init__(self, version, workspace_sid, workflow_sid): - """ - Initialize the WorkflowStatisticsList - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param workflow_sid: The workflow_sid +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 - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsList + @property + def _proxy(self) -> "WorkflowStatisticsContext": """ - super(WorkflowStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'workflow_sid': workflow_sid, } + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def get(self): + :returns: WorkflowStatisticsContext for this WorkflowStatisticsInstance """ - Constructs a WorkflowStatisticsContext + 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 - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsContext + 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": """ - return WorkflowStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - workflow_sid=self._solution['workflow_sid'], - ) + Fetch the WorkflowStatisticsInstance - def __call__(self): - """ - Constructs a WorkflowStatisticsContext + :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: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsContext + :returns: The fetched WorkflowStatisticsInstance """ - return WorkflowStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - workflow_sid=self._solution['workflow_sid'], + 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, ) - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class WorkflowStatisticsPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the WorkflowStatisticsPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The workspace_sid - :param workflow_sid: The workflow_sid - - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsPage - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsPage - """ - super(WorkflowStatisticsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): + 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": """ - Build an instance of WorkflowStatisticsInstance + Asynchronous coroutine to fetch the WorkflowStatisticsInstance - :param dict payload: Payload response from the API + :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: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsInstance + :returns: The fetched WorkflowStatisticsInstance """ - return WorkflowStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - workflow_sid=self._solution['workflow_sid'], + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) class WorkflowStatisticsContext(InstanceContext): - """ """ - def __init__(self, version, workspace_sid, workflow_sid): + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): """ Initialize the WorkflowStatisticsContext - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :param workflow_sid: The workflow_sid - - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.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(WorkflowStatisticsContext, self).__init__(version) + 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) + 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=values.unset, start_date=values.unset, - end_date=values.unset, task_channel=values.unset, - split_by_wait_time=values.unset): - """ - Fetch a WorkflowStatisticsInstance + 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, + } + ) - :param unicode minutes: The minutes - :param datetime start_date: The start_date - :param datetime end_date: The end_date - :param unicode task_channel: The task_channel - :param unicode split_by_wait_time: The split_by_wait_time + headers = values.of({}) - :returns: Fetched WorkflowStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsInstance - """ - params = 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["Accept"] = "application/json" payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], ) - def __repr__(self): - """ - Provide a friendly representation + 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, + } + ) - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + headers = values.of({}) + headers["Accept"] = "application/json" -class WorkflowStatisticsInstance(InstanceResource): - """ """ + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) - def __init__(self, version, payload, workspace_sid, workflow_sid): - """ - Initialize the WorkflowStatisticsInstance + return WorkflowStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsInstance + def __repr__(self) -> str: """ - super(WorkflowStatisticsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'cumulative': payload['cumulative'], - 'realtime': payload['realtime'], - 'workflow_sid': payload['workflow_sid'], - 'workspace_sid': payload['workspace_sid'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'workflow_sid': workflow_sid, } + Provide a friendly representation - @property - def _proxy(self): + :returns: Machine friendly representation """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: WorkflowStatisticsContext for this WorkflowStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsContext - """ - 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 - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] +class WorkflowStatisticsList(ListResource): - @property - def cumulative(self): + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): """ - :returns: The cumulative - :rtype: dict - """ - return self._properties['cumulative'] + Initialize the WorkflowStatisticsList - @property - def realtime(self): - """ - :returns: The realtime - :rtype: dict - """ - return self._properties['realtime'] + :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. - @property - def workflow_sid(self): """ - :returns: The workflow_sid - :rtype: unicode - """ - return self._properties['workflow_sid'] + super().__init__(version) - @property - def workspace_sid(self): - """ - :returns: The workspace_sid - :rtype: unicode - """ - return self._properties['workspace_sid'] + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } - @property - def url(self): + def get(self) -> WorkflowStatisticsContext: """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] + Constructs a WorkflowStatisticsContext - def fetch(self, minutes=values.unset, start_date=values.unset, - end_date=values.unset, task_channel=values.unset, - split_by_wait_time=values.unset): """ - Fetch a WorkflowStatisticsInstance + return WorkflowStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) - :param unicode minutes: The minutes - :param datetime start_date: The start_date - :param datetime end_date: The end_date - :param unicode task_channel: The task_channel - :param unicode split_by_wait_time: The split_by_wait_time + def __call__(self) -> WorkflowStatisticsContext: + """ + Constructs a WorkflowStatisticsContext - :returns: Fetched WorkflowStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.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, + return WorkflowStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py b/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py index 528b104b79..3747b395d2 100644 --- a/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py @@ -1,435 +1,356 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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.page import Page - - -class WorkspaceCumulativeStatisticsList(ListResource): - """ """ - - def __init__(self, version, workspace_sid): - """ - Initialize the WorkspaceCumulativeStatisticsList +from twilio.base.version import Version - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - :returns: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsList - """ - super(WorkspaceCumulativeStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } - - def get(self): - """ - Constructs a WorkspaceCumulativeStatisticsContext - - :returns: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsContext - """ - return WorkspaceCumulativeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], +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") ) - - def __call__(self): - """ - Constructs a WorkspaceCumulativeStatisticsContext - - :returns: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsContext - """ - return WorkspaceCumulativeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_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.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") - def __repr__(self): - """ - Provide a friendly representation + self._solution = { + "workspace_sid": workspace_sid, + } + self._context: Optional[WorkspaceCumulativeStatisticsContext] = None - :returns: Machine friendly representation - :rtype: str + @property + def _proxy(self) -> "WorkspaceCumulativeStatisticsContext": """ - return '' - + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context -class WorkspaceCumulativeStatisticsPage(Page): - """ """ + :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 __init__(self, version, response, 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": """ - Initialize the WorkspaceCumulativeStatisticsPage + Fetch the WorkspaceCumulativeStatisticsInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The workspace_sid + :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: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsPage - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsPage + :returns: The fetched WorkspaceCumulativeStatisticsInstance """ - super(WorkspaceCumulativeStatisticsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + 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, + ) - def get_instance(self, payload): + 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": """ - Build an instance of WorkspaceCumulativeStatisticsInstance + Asynchronous coroutine to fetch the WorkspaceCumulativeStatisticsInstance - :param dict payload: Payload response from the API + :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: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsInstance + :returns: The fetched WorkspaceCumulativeStatisticsInstance """ - return WorkspaceCumulativeStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) class WorkspaceCumulativeStatisticsContext(InstanceContext): - """ """ - def __init__(self, version, workspace_sid): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the WorkspaceCumulativeStatisticsContext - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - - :returns: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsContext + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace to fetch. """ - super(WorkspaceCumulativeStatisticsContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'workspace_sid': workspace_sid, } - self._uri = '/Workspaces/{workspace_sid}/CumulativeStatistics'.format(**self._solution) + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/CumulativeStatistics".format( + **self._solution + ) - def fetch(self, end_date=values.unset, minutes=values.unset, - start_date=values.unset, task_channel=values.unset, - split_by_wait_time=values.unset): - """ - Fetch a WorkspaceCumulativeStatisticsInstance + 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, + } + ) - :param datetime end_date: The end_date - :param unicode minutes: The minutes - :param datetime start_date: The start_date - :param unicode task_channel: The task_channel - :param unicode split_by_wait_time: The split_by_wait_time + headers = values.of({}) - :returns: Fetched WorkspaceCumulativeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsInstance - """ - params = 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["Accept"] = "application/json" payload = self._version.fetch( - 'GET', - self._uri, - params=params, + method="GET", uri=self._uri, params=data, headers=headers ) return WorkspaceCumulativeStatisticsInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], + workspace_sid=self._solution["workspace_sid"], ) - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class WorkspaceCumulativeStatisticsInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, workspace_sid): - """ - Initialize the WorkspaceCumulativeStatisticsInstance - - :returns: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsInstance - """ - super(WorkspaceCumulativeStatisticsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'avg_task_acceptance_time': deserialize.integer(payload['avg_task_acceptance_time']), - 'start_time': deserialize.iso8601_datetime(payload['start_time']), - 'end_time': deserialize.iso8601_datetime(payload['end_time']), - 'reservations_created': deserialize.integer(payload['reservations_created']), - 'reservations_accepted': deserialize.integer(payload['reservations_accepted']), - 'reservations_rejected': deserialize.integer(payload['reservations_rejected']), - 'reservations_timed_out': deserialize.integer(payload['reservations_timed_out']), - 'reservations_canceled': deserialize.integer(payload['reservations_canceled']), - 'reservations_rescinded': deserialize.integer(payload['reservations_rescinded']), - 'split_by_wait_time': payload['split_by_wait_time'], - 'wait_duration_until_accepted': payload['wait_duration_until_accepted'], - 'wait_duration_until_canceled': payload['wait_duration_until_canceled'], - 'tasks_canceled': deserialize.integer(payload['tasks_canceled']), - 'tasks_completed': deserialize.integer(payload['tasks_completed']), - 'tasks_created': deserialize.integer(payload['tasks_created']), - 'tasks_deleted': deserialize.integer(payload['tasks_deleted']), - 'tasks_moved': deserialize.integer(payload['tasks_moved']), - 'tasks_timed_out_in_workflow': deserialize.integer(payload['tasks_timed_out_in_workflow']), - 'workspace_sid': payload['workspace_sid'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsContext - """ - if self._context is None: - self._context = WorkspaceCumulativeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def avg_task_acceptance_time(self): - """ - :returns: The avg_task_acceptance_time - :rtype: unicode - """ - return self._properties['avg_task_acceptance_time'] - - @property - def start_time(self): - """ - :returns: The start_time - :rtype: datetime - """ - return self._properties['start_time'] - - @property - def end_time(self): - """ - :returns: The end_time - :rtype: datetime - """ - return self._properties['end_time'] - - @property - def reservations_created(self): - """ - :returns: The reservations_created - :rtype: unicode - """ - return self._properties['reservations_created'] - - @property - def reservations_accepted(self): - """ - :returns: The reservations_accepted - :rtype: unicode - """ - return self._properties['reservations_accepted'] - - @property - def reservations_rejected(self): - """ - :returns: The reservations_rejected - :rtype: unicode - """ - return self._properties['reservations_rejected'] + 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, + } + ) - @property - def reservations_timed_out(self): - """ - :returns: The reservations_timed_out - :rtype: unicode - """ - return self._properties['reservations_timed_out'] + headers = values.of({}) - @property - def reservations_canceled(self): - """ - :returns: The reservations_canceled - :rtype: unicode - """ - return self._properties['reservations_canceled'] + headers["Accept"] = "application/json" - @property - def reservations_rescinded(self): - """ - :returns: The reservations_rescinded - :rtype: unicode - """ - return self._properties['reservations_rescinded'] + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) - @property - def split_by_wait_time(self): - """ - :returns: The split_by_wait_time - :rtype: dict - """ - return self._properties['split_by_wait_time'] + return WorkspaceCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) - @property - def wait_duration_until_accepted(self): + def __repr__(self) -> str: """ - :returns: The wait_duration_until_accepted - :rtype: dict - """ - return self._properties['wait_duration_until_accepted'] + Provide a friendly representation - @property - def wait_duration_until_canceled(self): - """ - :returns: The wait_duration_until_canceled - :rtype: dict + :returns: Machine friendly representation """ - return self._properties['wait_duration_until_canceled'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) - @property - def tasks_canceled(self): - """ - :returns: The tasks_canceled - :rtype: unicode - """ - return self._properties['tasks_canceled'] - @property - def tasks_completed(self): - """ - :returns: The tasks_completed - :rtype: unicode - """ - return self._properties['tasks_completed'] +class WorkspaceCumulativeStatisticsList(ListResource): - @property - def tasks_created(self): - """ - :returns: The tasks_created - :rtype: unicode + def __init__(self, version: Version, workspace_sid: str): """ - return self._properties['tasks_created'] + Initialize the WorkspaceCumulativeStatisticsList - @property - def tasks_deleted(self): - """ - :returns: The tasks_deleted - :rtype: unicode - """ - return self._properties['tasks_deleted'] + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace to fetch. - @property - def tasks_moved(self): - """ - :returns: The tasks_moved - :rtype: unicode """ - return self._properties['tasks_moved'] + super().__init__(version) - @property - def tasks_timed_out_in_workflow(self): - """ - :returns: The tasks_timed_out_in_workflow - :rtype: unicode - """ - return self._properties['tasks_timed_out_in_workflow'] + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } - @property - def workspace_sid(self): + def get(self) -> WorkspaceCumulativeStatisticsContext: """ - :returns: The workspace_sid - :rtype: unicode - """ - return self._properties['workspace_sid'] + Constructs a WorkspaceCumulativeStatisticsContext - @property - def url(self): """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] + return WorkspaceCumulativeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) - def fetch(self, end_date=values.unset, minutes=values.unset, - start_date=values.unset, task_channel=values.unset, - split_by_wait_time=values.unset): + def __call__(self) -> WorkspaceCumulativeStatisticsContext: """ - Fetch a WorkspaceCumulativeStatisticsInstance - - :param datetime end_date: The end_date - :param unicode minutes: The minutes - :param datetime start_date: The start_date - :param unicode task_channel: The task_channel - :param unicode split_by_wait_time: The split_by_wait_time + Constructs a WorkspaceCumulativeStatisticsContext - :returns: Fetched WorkspaceCumulativeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.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, + return WorkspaceCumulativeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/taskrouter/v1/workspace/workspace_real_time_statistics.py b/twilio/rest/taskrouter/v1/workspace/workspace_real_time_statistics.py index 9918df601b..923a94bf3a 100644 --- a/twilio/rest/taskrouter/v1/workspace/workspace_real_time_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workspace_real_time_statistics.py @@ -1,302 +1,259 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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.page import Page - - -class WorkspaceRealTimeStatisticsList(ListResource): - """ """ +from twilio.base.version import Version - def __init__(self, version, workspace_sid): - """ - Initialize the WorkspaceRealTimeStatisticsList - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - - :returns: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsList - """ - super(WorkspaceRealTimeStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } - - def get(self): - """ - Constructs a WorkspaceRealTimeStatisticsContext - - :returns: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsContext - """ - return WorkspaceRealTimeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], +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" ) - - def __call__(self): - """ - Constructs a WorkspaceRealTimeStatisticsContext - - :returns: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsContext - """ - return WorkspaceRealTimeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_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.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") - def __repr__(self): - """ - Provide a friendly representation + self._solution = { + "workspace_sid": workspace_sid, + } + self._context: Optional[WorkspaceRealTimeStatisticsContext] = None - :returns: Machine friendly representation - :rtype: str + @property + def _proxy(self) -> "WorkspaceRealTimeStatisticsContext": """ - return '' - + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context -class WorkspaceRealTimeStatisticsPage(Page): - """ """ + :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 __init__(self, version, response, solution): + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> "WorkspaceRealTimeStatisticsInstance": """ - Initialize the WorkspaceRealTimeStatisticsPage + Fetch the WorkspaceRealTimeStatisticsInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The workspace_sid + :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: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsPage - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsPage + :returns: The fetched WorkspaceRealTimeStatisticsInstance """ - super(WorkspaceRealTimeStatisticsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch( + task_channel=task_channel, + ) - def get_instance(self, payload): + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> "WorkspaceRealTimeStatisticsInstance": """ - Build an instance of WorkspaceRealTimeStatisticsInstance + Asynchronous coroutine to fetch the WorkspaceRealTimeStatisticsInstance - :param dict payload: Payload response from the API + :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: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsInstance + :returns: The fetched WorkspaceRealTimeStatisticsInstance """ - return WorkspaceRealTimeStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], + return await self._proxy.fetch_async( + task_channel=task_channel, ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) class WorkspaceRealTimeStatisticsContext(InstanceContext): - """ """ - def __init__(self, version, workspace_sid): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the WorkspaceRealTimeStatisticsContext - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - - :returns: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsContext + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace to fetch. """ - super(WorkspaceRealTimeStatisticsContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'workspace_sid': workspace_sid, } - self._uri = '/Workspaces/{workspace_sid}/RealTimeStatistics'.format(**self._solution) + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/RealTimeStatistics".format( + **self._solution + ) - def fetch(self, task_channel=values.unset): + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> WorkspaceRealTimeStatisticsInstance: """ - Fetch a WorkspaceRealTimeStatisticsInstance + Fetch the WorkspaceRealTimeStatisticsInstance - :param unicode task_channel: The task_channel + :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: Fetched WorkspaceRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsInstance + :returns: The fetched WorkspaceRealTimeStatisticsInstance """ - params = values.of({'TaskChannel': task_channel, }) + + data = values.of( + { + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" payload = self._version.fetch( - 'GET', - self._uri, - params=params, + method="GET", uri=self._uri, params=data, headers=headers ) return WorkspaceRealTimeStatisticsInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], + workspace_sid=self._solution["workspace_sid"], ) - def __repr__(self): + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> WorkspaceRealTimeStatisticsInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the WorkspaceRealTimeStatisticsInstance - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + :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 + """ -class WorkspaceRealTimeStatisticsInstance(InstanceResource): - """ """ + data = values.of( + { + "TaskChannel": task_channel, + } + ) - def __init__(self, version, payload, workspace_sid): - """ - Initialize the WorkspaceRealTimeStatisticsInstance + headers = values.of({}) - :returns: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsInstance - """ - super(WorkspaceRealTimeStatisticsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'activity_statistics': payload['activity_statistics'], - 'longest_task_waiting_age': deserialize.integer(payload['longest_task_waiting_age']), - 'tasks_by_priority': payload['tasks_by_priority'], - 'tasks_by_status': payload['tasks_by_status'], - 'total_tasks': deserialize.integer(payload['total_tasks']), - 'total_workers': deserialize.integer(payload['total_workers']), - 'workspace_sid': payload['workspace_sid'], - 'url': payload['url'], - } + headers["Accept"] = "application/json" - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, } + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + return WorkspaceRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) - :returns: WorkspaceRealTimeStatisticsContext for this WorkspaceRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsContext + def __repr__(self) -> str: """ - if self._context is None: - self._context = WorkspaceRealTimeStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - ) - return self._context + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) - @property - def activity_statistics(self): - """ - :returns: The activity_statistics - :rtype: dict - """ - return self._properties['activity_statistics'] - @property - def longest_task_waiting_age(self): - """ - :returns: The longest_task_waiting_age - :rtype: unicode - """ - return self._properties['longest_task_waiting_age'] +class WorkspaceRealTimeStatisticsList(ListResource): - @property - def tasks_by_priority(self): + def __init__(self, version: Version, workspace_sid: str): """ - :returns: The tasks_by_priority - :rtype: dict - """ - return self._properties['tasks_by_priority'] + Initialize the WorkspaceRealTimeStatisticsList - @property - def tasks_by_status(self): - """ - :returns: The tasks_by_status - :rtype: dict - """ - return self._properties['tasks_by_status'] + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace to fetch. - @property - def total_tasks(self): """ - :returns: The total_tasks - :rtype: unicode - """ - return self._properties['total_tasks'] + super().__init__(version) - @property - def total_workers(self): - """ - :returns: The total_workers - :rtype: unicode - """ - return self._properties['total_workers'] + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } - @property - def workspace_sid(self): + def get(self) -> WorkspaceRealTimeStatisticsContext: """ - :returns: The workspace_sid - :rtype: unicode - """ - return self._properties['workspace_sid'] + Constructs a WorkspaceRealTimeStatisticsContext - @property - def url(self): """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] + return WorkspaceRealTimeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) - def fetch(self, task_channel=values.unset): + def __call__(self) -> WorkspaceRealTimeStatisticsContext: """ - Fetch a WorkspaceRealTimeStatisticsInstance - - :param unicode task_channel: The task_channel + Constructs a WorkspaceRealTimeStatisticsContext - :returns: Fetched WorkspaceRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsInstance """ - return self._proxy.fetch(task_channel=task_channel, ) + return WorkspaceRealTimeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py b/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py index f5c511b30e..b8414a5c6c 100644 --- a/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py @@ -1,284 +1,282 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import serialize -from twilio.base import values +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.page import Page +from twilio.base.version import Version -class WorkspaceStatisticsList(ListResource): - """ """ +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 - def __init__(self, version, workspace_sid): + @property + def _proxy(self) -> "WorkspaceStatisticsContext": """ - Initialize the WorkspaceStatisticsList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid + :returns: WorkspaceStatisticsContext for this WorkspaceStatisticsInstance + """ + if self._context is None: + self._context = WorkspaceStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + ) + return self._context - :returns: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsList + 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": """ - super(WorkspaceStatisticsList, self).__init__(version) + Fetch the WorkspaceStatisticsInstance - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } + :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. - def get(self): + :returns: The fetched WorkspaceStatisticsInstance """ - Constructs a WorkspaceStatisticsContext + 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, + ) - :returns: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsContext + 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": """ - return WorkspaceStatisticsContext(self._version, workspace_sid=self._solution['workspace_sid'], ) + Asynchronous coroutine to fetch the WorkspaceStatisticsInstance - def __call__(self): - """ - Constructs a WorkspaceStatisticsContext + :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: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsContext + :returns: The fetched WorkspaceStatisticsInstance """ - return WorkspaceStatisticsContext(self._version, workspace_sid=self._solution['workspace_sid'], ) + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class WorkspaceStatisticsPage(Page): - """ """ +class WorkspaceStatisticsContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, workspace_sid: str): """ - Initialize the WorkspaceStatisticsPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The workspace_sid + Initialize the WorkspaceStatisticsContext - :returns: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsPage - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsPage + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace to fetch. """ - super(WorkspaceStatisticsPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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, + } + ) - def get_instance(self, payload): - """ - Build an instance of WorkspaceStatisticsInstance + headers = values.of({}) - :param dict payload: Payload response from the API + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) - :returns: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsInstance - """ return WorkspaceStatisticsInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], + workspace_sid=self._solution["workspace_sid"], ) - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class WorkspaceStatisticsContext(InstanceContext): - """ """ - - def __init__(self, version, workspace_sid): - """ - Initialize the WorkspaceStatisticsContext - - :param Version version: Version that contains the resource - :param workspace_sid: The workspace_sid - - :returns: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsContext - """ - super(WorkspaceStatisticsContext, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } - self._uri = '/Workspaces/{workspace_sid}/Statistics'.format(**self._solution) + 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, + } + ) - def fetch(self, minutes=values.unset, start_date=values.unset, - end_date=values.unset, task_channel=values.unset, - split_by_wait_time=values.unset): - """ - Fetch a WorkspaceStatisticsInstance + headers = values.of({}) - :param unicode minutes: The minutes - :param datetime start_date: The start_date - :param datetime end_date: The end_date - :param unicode task_channel: The task_channel - :param unicode split_by_wait_time: The split_by_wait_time + headers["Accept"] = "application/json" - :returns: Fetched WorkspaceStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsInstance - """ - params = values.of({ - 'Minutes': minutes, - 'StartDate': serialize.iso8601_datetime(start_date), - 'EndDate': serialize.iso8601_datetime(end_date), - 'TaskChannel': task_channel, - 'SplitByWaitTime': split_by_wait_time, - }) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + workspace_sid=self._solution["workspace_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class WorkspaceStatisticsInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, workspace_sid): - """ - Initialize the WorkspaceStatisticsInstance - - :returns: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsInstance """ - super(WorkspaceStatisticsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'realtime': payload['realtime'], - 'cumulative': payload['cumulative'], - 'account_sid': payload['account_sid'], - 'workspace_sid': payload['workspace_sid'], - 'url': payload['url'], - } + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, } - @property - def _proxy(self): - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context +class WorkspaceStatisticsList(ListResource): - :returns: WorkspaceStatisticsContext for this WorkspaceStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsContext + def __init__(self, version: Version, workspace_sid: str): """ - if self._context is None: - self._context = WorkspaceStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - ) - return self._context + Initialize the WorkspaceStatisticsList - @property - def realtime(self): - """ - :returns: The realtime - :rtype: dict - """ - return self._properties['realtime'] + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace to fetch. - @property - def cumulative(self): - """ - :returns: The cumulative - :rtype: dict """ - return self._properties['cumulative'] + super().__init__(version) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } - @property - def workspace_sid(self): + def get(self) -> WorkspaceStatisticsContext: """ - :returns: The workspace_sid - :rtype: unicode - """ - return self._properties['workspace_sid'] + Constructs a WorkspaceStatisticsContext - @property - def url(self): - """ - :returns: The url - :rtype: unicode """ - return self._properties['url'] + return WorkspaceStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) - def fetch(self, minutes=values.unset, start_date=values.unset, - end_date=values.unset, task_channel=values.unset, - split_by_wait_time=values.unset): + def __call__(self) -> WorkspaceStatisticsContext: """ - Fetch a WorkspaceStatisticsInstance - - :param unicode minutes: The minutes - :param datetime start_date: The start_date - :param datetime end_date: The end_date - :param unicode task_channel: The task_channel - :param unicode split_by_wait_time: The split_by_wait_time + Constructs a WorkspaceStatisticsContext - :returns: Fetched WorkspaceStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_statistics.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, + return WorkspaceStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 "" diff --git a/twilio/rest/trunking/__init__.py b/twilio/rest/trunking/__init__.py index 9134532820..14bd6be655 100644 --- a/twilio/rest/trunking/__init__.py +++ b/twilio/rest/trunking/__init__.py @@ -1,53 +1,15 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" +from warnings import warn -from twilio.base.domain import Domain -from twilio.rest.trunking.v1 import V1 +from twilio.rest.trunking.TrunkingBase import TrunkingBase +from twilio.rest.trunking.v1.trunk import TrunkList -class Trunking(Domain): - - def __init__(self, twilio): - """ - Initialize the Trunking Domain - - :returns: Domain for Trunking - :rtype: twilio.rest.trunking.Trunking - """ - super(Trunking, self).__init__(twilio) - - self.base_url = 'https://trunking.twilio.com' - - # Versions - self._v1 = None - +class Trunking(TrunkingBase): @property - def v1(self): - """ - :returns: Version v1 of trunking - :rtype: twilio.rest.trunking.v1.V1 - """ - if self._v1 is None: - self._v1 = V1(self) - return self._v1 - - @property - def trunks(self): - """ - :rtype: twilio.rest.trunking.v1.trunk.TrunkList - """ + def trunks(self) -> TrunkList: + warn( + "trunks is deprecated. Use v1.trunks instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v1.trunks - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/trunking/v1/__init__.py b/twilio/rest/trunking/v1/__init__.py index ca3694a089..af530b97c7 100644 --- a/twilio/rest/trunking/v1/__init__.py +++ b/twilio/rest/trunking/v1/__init__.py @@ -1,42 +1,43 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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): + def __init__(self, domain: Domain): """ Initialize the V1 version of Trunking - :returns: V1 version of Trunking - :rtype: twilio.rest.trunking.v1.V1.V1 + :param domain: The Twilio.trunking domain """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._trunks = None + super().__init__(domain, "v1") + self._trunks: Optional[TrunkList] = None @property - def trunks(self): - """ - :rtype: twilio.rest.trunking.v1.trunk.TrunkList - """ + def trunks(self) -> TrunkList: if self._trunks is None: self._trunks = TrunkList(self) return self._trunks - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/trunking/v1/trunk/__init__.py b/twilio/rest/trunking/v1/trunk/__init__.py index a4d09dc4e1..6a93a83233 100644 --- a/twilio/rest/trunking/v1/trunk/__init__.py +++ b/twilio/rest/trunking/v1/trunk/__init__.py @@ -1,623 +1,887 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 TrunkList(ListResource): - """ """ +class TrunkInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the TrunkList + 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") - :param Version version: Version that contains the resource + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[TrunkContext] = None - :returns: twilio.rest.trunking.v1.trunk.TrunkList - :rtype: twilio.rest.trunking.v1.trunk.TrunkList + @property + def _proxy(self) -> "TrunkContext": """ - super(TrunkList, self).__init__(version) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - # Path Solution - self._solution = {} - self._uri = '/Trunks'.format(**self._solution) - - def create(self, friendly_name=values.unset, domain_name=values.unset, - disaster_recovery_url=values.unset, - disaster_recovery_method=values.unset, recording=values.unset, - secure=values.unset): - """ - Create a new TrunkInstance - - :param unicode friendly_name: The friendly_name - :param unicode domain_name: The domain_name - :param unicode disaster_recovery_url: The disaster_recovery_url - :param unicode disaster_recovery_method: The disaster_recovery_method - :param unicode recording: The recording - :param bool secure: The secure - - :returns: Newly created TrunkInstance - :rtype: twilio.rest.trunking.v1.trunk.TrunkInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'DomainName': domain_name, - 'DisasterRecoveryUrl': disaster_recovery_url, - 'DisasterRecoveryMethod': disaster_recovery_method, - 'Recording': recording, - 'Secure': secure, - }) + :returns: TrunkContext for this TrunkInstance + """ + if self._context is None: + self._context = TrunkContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + def delete(self) -> bool: + """ + Deletes the TrunkInstance - return TrunkInstance(self._version, payload, ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.trunking.v1.trunk.TrunkInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the TrunkInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the TrunkInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.trunking.v1.trunk.TrunkInstance] + :returns: The fetched TrunkInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_async(self) -> "TrunkInstance": """ - Retrieve a single page of TrunkInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the TrunkInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of TrunkInstance - :rtype: twilio.rest.trunking.v1.trunk.TrunkPage + :returns: The fetched TrunkInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return TrunkPage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def get_page(self, target_url): + 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": """ - Retrieve a specific page of TrunkInstance records from the API. - Request is executed immediately + Update the TrunkInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of TrunkInstance - :rtype: twilio.rest.trunking.v1.trunk.TrunkPage + :returns: The updated TrunkInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, ) - return TrunkPage(self._version, response, self._solution) + 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, + ) - def get(self, sid): + @property + def credentials_lists(self) -> CredentialListList: """ - Constructs a TrunkContext - - :param sid: The sid + Access the credentials_lists + """ + return self._proxy.credentials_lists - :returns: twilio.rest.trunking.v1.trunk.TrunkContext - :rtype: twilio.rest.trunking.v1.trunk.TrunkContext + @property + def ip_access_control_lists(self) -> IpAccessControlListList: """ - return TrunkContext(self._version, sid=sid, ) + Access the ip_access_control_lists + """ + return self._proxy.ip_access_control_lists - def __call__(self, sid): + @property + def origination_urls(self) -> OriginationUrlList: """ - Constructs a TrunkContext + Access the origination_urls + """ + return self._proxy.origination_urls - :param sid: The sid + @property + def phone_numbers(self) -> PhoneNumberList: + """ + Access the phone_numbers + """ + return self._proxy.phone_numbers - :returns: twilio.rest.trunking.v1.trunk.TrunkContext - :rtype: twilio.rest.trunking.v1.trunk.TrunkContext + @property + def recordings(self) -> RecordingList: + """ + Access the recordings """ - return TrunkContext(self._version, sid=sid, ) + return self._proxy.recordings - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class TrunkPage(Page): - """ """ +class TrunkContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the TrunkPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the TrunkContext - :returns: twilio.rest.trunking.v1.trunk.TrunkPage - :rtype: twilio.rest.trunking.v1.trunk.TrunkPage + :param version: Version that contains the resource + :param sid: The unique string that we created to identify the OriginationUrl resource to update. """ - super(TrunkPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of TrunkInstance + Deletes the TrunkInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.trunking.v1.trunk.TrunkInstance - :rtype: twilio.rest.trunking.v1.trunk.TrunkInstance + :returns: True if delete succeeds, False otherwise """ - return TrunkInstance(self._version, payload, ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the TrunkInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class TrunkContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, sid): + def fetch(self) -> TrunkInstance: """ - Initialize the TrunkContext + Fetch the TrunkInstance - :param Version version: Version that contains the resource - :param sid: The sid - :returns: twilio.rest.trunking.v1.trunk.TrunkContext - :rtype: twilio.rest.trunking.v1.trunk.TrunkContext + :returns: The fetched TrunkInstance """ - super(TrunkContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Trunks/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - # Dependents - self._origination_urls = None - self._credentials_lists = None - self._ip_access_control_lists = None - self._phone_numbers = None + return TrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def fetch(self): + async def fetch_async(self) -> TrunkInstance: """ - Fetch a TrunkInstance + Asynchronous coroutine to fetch the TrunkInstance + - :returns: Fetched TrunkInstance - :rtype: twilio.rest.trunking.v1.trunk.TrunkInstance + :returns: The fetched TrunkInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) + headers = values.of({}) - return TrunkInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" - def delete(self): - """ - Deletes the TrunkInstance + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + return TrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def update(self, friendly_name=values.unset, domain_name=values.unset, - disaster_recovery_url=values.unset, - disaster_recovery_method=values.unset, recording=values.unset, - secure=values.unset): + 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 unicode friendly_name: The friendly_name - :param unicode domain_name: The domain_name - :param unicode disaster_recovery_url: The disaster_recovery_url - :param unicode disaster_recovery_method: The disaster_recovery_method - :param unicode recording: The recording - :param bool secure: The secure - - :returns: Updated TrunkInstance - :rtype: twilio.rest.trunking.v1.trunk.TrunkInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'DomainName': domain_name, - 'DisasterRecoveryUrl': disaster_recovery_url, - 'DisasterRecoveryMethod': disaster_recovery_method, - 'Recording': recording, - 'Secure': secure, - }) + :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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) - return TrunkInstance(self._version, payload, sid=self._solution['sid'], ) + 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({}) - @property - def origination_urls(self): - """ - Access the origination_urls + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlList - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlList - """ - if self._origination_urls is None: - self._origination_urls = OriginationUrlList(self._version, trunk_sid=self._solution['sid'], ) - return self._origination_urls + 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): + def credentials_lists(self) -> CredentialListList: """ Access the credentials_lists - - :returns: twilio.rest.trunking.v1.trunk.credential_list.CredentialListList - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListList """ if self._credentials_lists is None: - self._credentials_lists = CredentialListList(self._version, trunk_sid=self._solution['sid'], ) + self._credentials_lists = CredentialListList( + self._version, + self._solution["sid"], + ) return self._credentials_lists @property - def ip_access_control_lists(self): + def ip_access_control_lists(self) -> IpAccessControlListList: """ Access the ip_access_control_lists - - :returns: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListList - :rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListList """ if self._ip_access_control_lists is None: self._ip_access_control_lists = IpAccessControlListList( self._version, - trunk_sid=self._solution['sid'], + self._solution["sid"], ) return self._ip_access_control_lists @property - def phone_numbers(self): + def origination_urls(self) -> OriginationUrlList: """ - Access the phone_numbers + Access the origination_urls + """ + if self._origination_urls is None: + self._origination_urls = OriginationUrlList( + self._version, + self._solution["sid"], + ) + return self._origination_urls - :returns: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberList - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberList + @property + def phone_numbers(self) -> PhoneNumberList: + """ + Access the phone_numbers """ if self._phone_numbers is None: - self._phone_numbers = PhoneNumberList(self._version, trunk_sid=self._solution['sid'], ) + self._phone_numbers = PhoneNumberList( + self._version, + self._solution["sid"], + ) return self._phone_numbers - def __repr__(self): + @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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class TrunkInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, sid=None): - """ - Initialize the TrunkInstance - - :returns: twilio.rest.trunking.v1.trunk.TrunkInstance - :rtype: twilio.rest.trunking.v1.trunk.TrunkInstance - """ - super(TrunkInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'domain_name': payload['domain_name'], - 'disaster_recovery_method': payload['disaster_recovery_method'], - 'disaster_recovery_url': payload['disaster_recovery_url'], - 'friendly_name': payload['friendly_name'], - 'secure': payload['secure'], - 'recording': payload['recording'], - 'auth_type': payload['auth_type'], - 'auth_type_set': payload['auth_type_set'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'sid': payload['sid'], - 'url': payload['url'], - 'links': payload['links'], - } - - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } +class TrunkPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> TrunkInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of TrunkInstance - :returns: TrunkContext for this TrunkInstance - :rtype: twilio.rest.trunking.v1.trunk.TrunkContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = TrunkContext(self._version, sid=self._solution['sid'], ) - return self._context + return TrunkInstance(self._version, payload) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def domain_name(self): - """ - :returns: The domain_name - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['domain_name'] + return "" - @property - def disaster_recovery_method(self): - """ - :returns: The disaster_recovery_method - :rtype: unicode - """ - return self._properties['disaster_recovery_method'] - @property - def disaster_recovery_url(self): - """ - :returns: The disaster_recovery_url - :rtype: unicode - """ - return self._properties['disaster_recovery_url'] +class TrunkList(ListResource): - @property - def friendly_name(self): + def __init__(self, version: Version): """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] + Initialize the TrunkList - @property - def secure(self): - """ - :returns: The secure - :rtype: bool - """ - return self._properties['secure'] + :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"}) - @property - def recording(self): - """ - :returns: The recording - :rtype: dict - """ - return self._properties['recording'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def auth_type(self): - """ - :returns: The auth_type - :rtype: unicode - """ - return self._properties['auth_type'] + headers["Accept"] = "application/json" - @property - def auth_type_set(self): - """ - :returns: The auth_type_set - :rtype: unicode - """ - return self._properties['auth_type_set'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + 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"}) - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def sid(self): + 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]: """ - :returns: The sid - :rtype: unicode + 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 """ - return self._properties['sid'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def url(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TrunkInstance]: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def links(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TrunkInstance]: """ - :returns: The links - :rtype: unicode + 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 self._properties['links'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - def fetch(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TrunkInstance]: """ - Fetch a 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: Fetched TrunkInstance - :rtype: twilio.rest.trunking.v1.trunk.TrunkInstance + :returns: list that will contain up to limit results """ - return self._proxy.fetch() + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - def delete(self): + 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: """ - Deletes the TrunkInstance + Retrieve a single page of TrunkInstance records from the API. + Request is executed immediately - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param page_token: PageToken provided by the API + :param page_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 """ - return self._proxy.delete() + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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) - def update(self, friendly_name=values.unset, domain_name=values.unset, - disaster_recovery_url=values.unset, - disaster_recovery_method=values.unset, recording=values.unset, - secure=values.unset): + 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: """ - Update the TrunkInstance + Asynchronously retrieve a single page of TrunkInstance records from the API. + Request is executed immediately - :param unicode friendly_name: The friendly_name - :param unicode domain_name: The domain_name - :param unicode disaster_recovery_url: The disaster_recovery_url - :param unicode disaster_recovery_method: The disaster_recovery_method - :param unicode recording: The recording - :param bool secure: The secure + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - :returns: Updated TrunkInstance - :rtype: twilio.rest.trunking.v1.trunk.TrunkInstance + :returns: Page of 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, - recording=recording, - secure=secure, + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } ) - @property - def origination_urls(self): + headers = values.of({"Content-Type": "application/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: """ - Access the origination_urls + Retrieve a specific page of TrunkInstance records from the API. + Request is executed immediately - :returns: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlList - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlList + :param target_url: API-generated URL for the requested results page + + :returns: Page of TrunkInstance """ - return self._proxy.origination_urls + response = self._version.domain.twilio.request("GET", target_url) + return TrunkPage(self._version, response) - @property - def credentials_lists(self): + async def get_page_async(self, target_url: str) -> TrunkPage: """ - Access the credentials_lists + 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: twilio.rest.trunking.v1.trunk.credential_list.CredentialListList - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListList + :returns: Page of TrunkInstance """ - return self._proxy.credentials_lists + response = await self._version.domain.twilio.request_async("GET", target_url) + return TrunkPage(self._version, response) - @property - def ip_access_control_lists(self): + def get(self, sid: str) -> TrunkContext: """ - Access the ip_access_control_lists + Constructs a TrunkContext - :returns: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListList - :rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListList + :param sid: The unique string that we created to identify the OriginationUrl resource to update. """ - return self._proxy.ip_access_control_lists + return TrunkContext(self._version, sid=sid) - @property - def phone_numbers(self): + def __call__(self, sid: str) -> TrunkContext: """ - Access the phone_numbers + Constructs a TrunkContext - :returns: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberList - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberList + :param sid: The unique string that we created to identify the OriginationUrl resource to update. """ - return self._proxy.phone_numbers + return TrunkContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/trunking/v1/trunk/credential_list.py b/twilio/rest/trunking/v1/trunk/credential_list.py index 70d6b1a66b..09ffc99260 100644 --- a/twilio/rest/trunking/v1/trunk/credential_list.py +++ b/twilio/rest/trunking/v1/trunk/credential_list.py @@ -1,396 +1,538 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 CredentialListList(ListResource): - """ """ +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 - def __init__(self, version, trunk_sid): + @property + def _proxy(self) -> "CredentialListContext": """ - Initialize the CredentialListList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param trunk_sid: The trunk_sid + :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 - :returns: twilio.rest.trunking.v1.trunk.credential_list.CredentialListList - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListList + def delete(self) -> bool: """ - super(CredentialListList, self).__init__(version) + Deletes the CredentialListInstance - # Path Solution - self._solution = {'trunk_sid': trunk_sid, } - self._uri = '/Trunks/{trunk_sid}/CredentialLists'.format(**self._solution) - def create(self, credential_list_sid): + :returns: True if delete succeeds, False otherwise """ - Create a new CredentialListInstance - - :param unicode credential_list_sid: The credential_list_sid + return self._proxy.delete() - :returns: Newly created CredentialListInstance - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListInstance + async def delete_async(self) -> bool: """ - data = values.of({'CredentialListSid': credential_list_sid, }) + Asynchronous coroutine that deletes the CredentialListInstance - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - return CredentialListInstance(self._version, payload, trunk_sid=self._solution['trunk_sid'], ) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def stream(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the CredentialListInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.trunking.v1.trunk.credential_list.CredentialListInstance] + :returns: The fetched CredentialListInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(page_size=limits['page_size'], ) + async def fetch_async(self) -> "CredentialListInstance": + """ + Asynchronous coroutine to fetch the CredentialListInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + return await self._proxy.fetch_async() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.trunking.v1.trunk.credential_list.CredentialListInstance] + def __repr__(self) -> str: """ - return list(self.stream(limit=limit, page_size=page_size, )) + Provide a friendly representation - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + :returns: Machine friendly representation """ - Retrieve a single page of CredentialListInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of CredentialListInstance - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListPage +class CredentialListContext(InstanceContext): + + def __init__(self, version: Version, trunk_sid: str, sid: str): """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the CredentialListContext - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + :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) - return CredentialListPage(self._version, response, self._solution) + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid, + } + self._uri = "/Trunks/{trunk_sid}/CredentialLists/{sid}".format(**self._solution) - def get_page(self, target_url): + def delete(self) -> bool: """ - Retrieve a specific page of CredentialListInstance records from the API. - Request is executed immediately + Deletes the CredentialListInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of CredentialListInstance - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListPage + :returns: True if delete succeeds, False otherwise """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return CredentialListPage(self._version, response, self._solution) + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def get(self, sid): + async def delete_async(self) -> bool: """ - Constructs a CredentialListContext + Asynchronous coroutine that deletes the CredentialListInstance - :param sid: The sid - :returns: twilio.rest.trunking.v1.trunk.credential_list.CredentialListContext - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListContext + :returns: True if delete succeeds, False otherwise """ - return CredentialListContext(self._version, trunk_sid=self._solution['trunk_sid'], sid=sid, ) - def __call__(self, sid): + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialListInstance: """ - Constructs a CredentialListContext + Fetch the CredentialListInstance - :param sid: The sid - :returns: twilio.rest.trunking.v1.trunk.credential_list.CredentialListContext - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListContext + :returns: The fetched CredentialListInstance """ - return CredentialListContext(self._version, trunk_sid=self._solution['trunk_sid'], sid=sid, ) - def __repr__(self): + 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: """ - Provide a friendly representation + Asynchronous coroutine to fetch the CredentialListInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched CredentialListInstance """ - return '' + headers = values.of({}) -class CredentialListPage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): - """ - Initialize the CredentialListPage + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param trunk_sid: The trunk_sid + return CredentialListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.trunking.v1.trunk.credential_list.CredentialListPage - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListPage + def __repr__(self) -> str: """ - super(CredentialListPage, self).__init__(version, response) + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Path Solution - self._solution = solution - def get_instance(self, payload): +class CredentialListPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialListInstance: """ Build an instance of CredentialListInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.trunking.v1.trunk.credential_list.CredentialListInstance - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListInstance + :param payload: Payload response from the API """ - return CredentialListInstance(self._version, payload, trunk_sid=self._solution['trunk_sid'], ) + return CredentialListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class CredentialListContext(InstanceContext): - """ """ +class CredentialListList(ListResource): - def __init__(self, version, trunk_sid, sid): + def __init__(self, version: Version, trunk_sid: str): """ - Initialize the CredentialListContext + Initialize the CredentialListList - :param Version version: Version that contains the resource - :param trunk_sid: The trunk_sid - :param sid: The sid + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to read the credential lists. - :returns: twilio.rest.trunking.v1.trunk.credential_list.CredentialListContext - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListContext """ - super(CredentialListContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'trunk_sid': trunk_sid, 'sid': sid, } - self._uri = '/Trunks/{trunk_sid}/CredentialLists/{sid}'.format(**self._solution) + self._solution = { + "trunk_sid": trunk_sid, + } + self._uri = "/Trunks/{trunk_sid}/CredentialLists".format(**self._solution) - def fetch(self): + def create(self, credential_list_sid: str) -> CredentialListInstance: """ - Fetch a CredentialListInstance + Create the CredentialListInstance - :returns: Fetched CredentialListInstance - :rtype: twilio.rest.trunking.v1.trunk.credential_list.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 """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], - sid=self._solution['sid'], + self._version, payload, trunk_sid=self._solution["trunk_sid"] ) - def delete(self): + async def create_async(self, credential_list_sid: str) -> CredentialListInstance: """ - Deletes the CredentialListInstance + Asynchronously create the CredentialListInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :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. - def __repr__(self): + :returns: The created CredentialListInstance """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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" -class CredentialListInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, payload, trunk_sid, sid=None): - """ - Initialize the CredentialListInstance + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: twilio.rest.trunking.v1.trunk.credential_list.CredentialListInstance - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListInstance - """ - super(CredentialListInstance, self).__init__(version) + return CredentialListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'sid': payload['sid'], - 'trunk_sid': payload['trunk_sid'], - 'friendly_name': payload['friendly_name'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - } + 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. - # Context - self._context = None - self._solution = {'trunk_sid': trunk_sid, 'sid': sid or self._properties['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) - @property - def _proxy(self): + :returns: Generator that will yield up to limit results """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - :returns: CredentialListContext for this CredentialListInstance - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListContext - """ - if self._context is None: - self._context = CredentialListContext( - self._version, - trunk_sid=self._solution['trunk_sid'], - sid=self._solution['sid'], - ) - return self._context + return self._version.stream(page, limits["limit"]) - @property - def account_sid(self): + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialListInstance]: """ - :returns: The account_sid - :rtype: unicode + 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 """ - return self._properties['account_sid'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def sid(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialListInstance]: """ - :returns: The sid - :rtype: unicode + 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 self._properties['sid'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def trunk_sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialListInstance]: """ - :returns: The trunk_sid - :rtype: unicode + 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 self._properties['trunk_sid'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def friendly_name(self): + 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: """ - :returns: The friendly_name - :rtype: unicode + 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 """ - return self._properties['friendly_name'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def date_created(self): + headers = values.of({"Content-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: """ - :returns: The date_created - :rtype: datetime + 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 """ - return self._properties['date_created'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def date_updated(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The date_updated - :rtype: datetime + 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 """ - return self._properties['date_updated'] + response = self._version.domain.twilio.request("GET", target_url) + return CredentialListPage(self._version, response, self._solution) - @property - def url(self): + async def get_page_async(self, target_url: str) -> CredentialListPage: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialListPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> CredentialListContext: """ - Fetch a CredentialListInstance + Constructs a CredentialListContext - :returns: Fetched CredentialListInstance - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListInstance + :param sid: The unique string that we created to identify the CredentialList resource to fetch. """ - return self._proxy.fetch() + return CredentialListContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) - def delete(self): + def __call__(self, sid: str) -> CredentialListContext: """ - Deletes the CredentialListInstance + Constructs a CredentialListContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The unique string that we created to identify the CredentialList resource to fetch. """ - return self._proxy.delete() + return CredentialListContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/trunking/v1/trunk/ip_access_control_list.py b/twilio/rest/trunking/v1/trunk/ip_access_control_list.py index e9ca55f085..ec5a59de69 100644 --- a/twilio/rest/trunking/v1/trunk/ip_access_control_list.py +++ b/twilio/rest/trunking/v1/trunk/ip_access_control_list.py @@ -1,396 +1,542 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 IpAccessControlListList(ListResource): - """ """ +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 - def __init__(self, version, trunk_sid): + @property + def _proxy(self) -> "IpAccessControlListContext": """ - Initialize the IpAccessControlListList + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param Version version: Version that contains the resource - :param trunk_sid: The trunk_sid + :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 - :returns: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListList - :rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListList + def delete(self) -> bool: """ - super(IpAccessControlListList, self).__init__(version) + Deletes the IpAccessControlListInstance - # 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): + :returns: True if delete succeeds, False otherwise """ - Create a new IpAccessControlListInstance - - :param unicode ip_access_control_list_sid: The ip_access_control_list_sid + return self._proxy.delete() - :returns: Newly created IpAccessControlListInstance - :rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListInstance + async def delete_async(self) -> bool: """ - data = values.of({'IpAccessControlListSid': ip_access_control_list_sid, }) + Asynchronous coroutine that deletes the IpAccessControlListInstance - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - return IpAccessControlListInstance(self._version, payload, trunk_sid=self._solution['trunk_sid'], ) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def stream(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the IpAccessControlListInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListInstance] + :returns: The fetched IpAccessControlListInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(page_size=limits['page_size'], ) + async def fetch_async(self) -> "IpAccessControlListInstance": + """ + Asynchronous coroutine to fetch the IpAccessControlListInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + return await self._proxy.fetch_async() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListInstance] + def __repr__(self) -> str: """ - return list(self.stream(limit=limit, page_size=page_size, )) + Provide a friendly representation - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + :returns: Machine friendly representation """ - Retrieve a single page of IpAccessControlListInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of IpAccessControlListInstance - :rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListPage +class IpAccessControlListContext(InstanceContext): + + def __init__(self, version: Version, trunk_sid: str, sid: str): """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the IpAccessControlListContext - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + :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) - return IpAccessControlListPage(self._version, response, self._solution) + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid, + } + self._uri = "/Trunks/{trunk_sid}/IpAccessControlLists/{sid}".format( + **self._solution + ) - def get_page(self, target_url): + def delete(self) -> bool: """ - Retrieve a specific page of IpAccessControlListInstance records from the API. - Request is executed immediately + Deletes the IpAccessControlListInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of IpAccessControlListInstance - :rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListPage + :returns: True if delete succeeds, False otherwise """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return IpAccessControlListPage(self._version, response, self._solution) + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def get(self, sid): + async def delete_async(self) -> bool: """ - Constructs a IpAccessControlListContext + Asynchronous coroutine that deletes the IpAccessControlListInstance - :param sid: The sid - :returns: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListContext - :rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListContext + :returns: True if delete succeeds, False otherwise """ - return IpAccessControlListContext(self._version, trunk_sid=self._solution['trunk_sid'], sid=sid, ) - def __call__(self, sid): + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> IpAccessControlListInstance: """ - Constructs a IpAccessControlListContext + Fetch the IpAccessControlListInstance - :param sid: The sid - :returns: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListContext - :rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListContext + :returns: The fetched IpAccessControlListInstance """ - return IpAccessControlListContext(self._version, trunk_sid=self._solution['trunk_sid'], sid=sid, ) - def __repr__(self): + 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: """ - Provide a friendly representation + Asynchronous coroutine to fetch the IpAccessControlListInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched IpAccessControlListInstance """ - return '' + headers = values.of({}) -class IpAccessControlListPage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): - """ - Initialize the IpAccessControlListPage + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param trunk_sid: The trunk_sid + return IpAccessControlListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListPage - :rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListPage + def __repr__(self) -> str: """ - super(IpAccessControlListPage, self).__init__(version, response) + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Path Solution - self._solution = solution - def get_instance(self, payload): +class IpAccessControlListPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> IpAccessControlListInstance: """ Build an instance of IpAccessControlListInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListInstance - :rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListInstance + :param payload: Payload response from the API """ - return IpAccessControlListInstance(self._version, payload, trunk_sid=self._solution['trunk_sid'], ) + return IpAccessControlListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class IpAccessControlListContext(InstanceContext): - """ """ +class IpAccessControlListList(ListResource): - def __init__(self, version, trunk_sid, sid): + def __init__(self, version: Version, trunk_sid: str): """ - Initialize the IpAccessControlListContext + Initialize the IpAccessControlListList - :param Version version: Version that contains the resource - :param trunk_sid: The trunk_sid - :param sid: The sid + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to read the IP Access Control Lists. - :returns: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListContext - :rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListContext """ - super(IpAccessControlListContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'trunk_sid': trunk_sid, 'sid': sid, } - self._uri = '/Trunks/{trunk_sid}/IpAccessControlLists/{sid}'.format(**self._solution) + self._solution = { + "trunk_sid": trunk_sid, + } + self._uri = "/Trunks/{trunk_sid}/IpAccessControlLists".format(**self._solution) - def fetch(self): + def create(self, ip_access_control_list_sid: str) -> IpAccessControlListInstance: """ - Fetch a IpAccessControlListInstance + Create the IpAccessControlListInstance - :returns: Fetched IpAccessControlListInstance - :rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.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 """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], - sid=self._solution['sid'], + self._version, payload, trunk_sid=self._solution["trunk_sid"] ) - def delete(self): + async def create_async( + self, ip_access_control_list_sid: str + ) -> IpAccessControlListInstance: """ - Deletes the IpAccessControlListInstance + Asynchronously create the IpAccessControlListInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :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. - def __repr__(self): + :returns: The created IpAccessControlListInstance """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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" -class IpAccessControlListInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, payload, trunk_sid, sid=None): - """ - Initialize the IpAccessControlListInstance + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListInstance - :rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListInstance - """ - super(IpAccessControlListInstance, self).__init__(version) + return IpAccessControlListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'sid': payload['sid'], - 'trunk_sid': payload['trunk_sid'], - 'friendly_name': payload['friendly_name'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - } + 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. - # Context - self._context = None - self._solution = {'trunk_sid': trunk_sid, 'sid': sid or self._properties['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) - @property - def _proxy(self): + :returns: Generator that will yield up to limit results """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - :returns: IpAccessControlListContext for this IpAccessControlListInstance - :rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListContext - """ - if self._context is None: - self._context = IpAccessControlListContext( - self._version, - trunk_sid=self._solution['trunk_sid'], - sid=self._solution['sid'], - ) - return self._context + return self._version.stream(page, limits["limit"]) - @property - def account_sid(self): + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[IpAccessControlListInstance]: """ - :returns: The account_sid - :rtype: unicode + 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 """ - return self._properties['account_sid'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def sid(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAccessControlListInstance]: """ - :returns: The sid - :rtype: unicode + 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 self._properties['sid'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def trunk_sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAccessControlListInstance]: """ - :returns: The trunk_sid - :rtype: unicode + 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 self._properties['trunk_sid'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def friendly_name(self): + 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: """ - :returns: The friendly_name - :rtype: unicode + 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 """ - return self._properties['friendly_name'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def date_created(self): + headers = values.of({"Content-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: """ - :returns: The date_created - :rtype: datetime + 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 """ - return self._properties['date_created'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def date_updated(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The date_updated - :rtype: datetime + 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 """ - return self._properties['date_updated'] + response = self._version.domain.twilio.request("GET", target_url) + return IpAccessControlListPage(self._version, response, self._solution) - @property - def url(self): + async def get_page_async(self, target_url: str) -> IpAccessControlListPage: """ - :returns: The url - :rtype: unicode + 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 """ - return self._properties['url'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return IpAccessControlListPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> IpAccessControlListContext: """ - Fetch a IpAccessControlListInstance + Constructs a IpAccessControlListContext - :returns: Fetched IpAccessControlListInstance - :rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListInstance + :param sid: The unique string that we created to identify the IpAccessControlList resource to fetch. """ - return self._proxy.fetch() + return IpAccessControlListContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) - def delete(self): + def __call__(self, sid: str) -> IpAccessControlListContext: """ - Deletes the IpAccessControlListInstance + Constructs a IpAccessControlListContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The unique string that we created to identify the IpAccessControlList resource to fetch. """ - return self._proxy.delete() + return IpAccessControlListContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/trunking/v1/trunk/origination_url.py b/twilio/rest/trunking/v1/trunk/origination_url.py index d8fd2c7ecc..082fa34beb 100644 --- a/twilio/rest/trunking/v1/trunk/origination_url.py +++ b/twilio/rest/trunking/v1/trunk/origination_url.py @@ -1,501 +1,722 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 OriginationUrlList(ListResource): - """ """ - - def __init__(self, version, trunk_sid): - """ - Initialize the OriginationUrlList +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") - :param Version version: Version that contains the resource - :param trunk_sid: The trunk_sid + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid or self.sid, + } + self._context: Optional[OriginationUrlContext] = None - :returns: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlList - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlList + @property + def _proxy(self) -> "OriginationUrlContext": """ - super(OriginationUrlList, self).__init__(version) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - # Path Solution - self._solution = {'trunk_sid': trunk_sid, } - self._uri = '/Trunks/{trunk_sid}/OriginationUrls'.format(**self._solution) + :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 create(self, weight, priority, enabled, friendly_name, sip_url): + def delete(self) -> bool: """ - Create a new OriginationUrlInstance + Deletes the OriginationUrlInstance - :param unicode weight: The weight - :param unicode priority: The priority - :param bool enabled: The enabled - :param unicode friendly_name: The friendly_name - :param unicode sip_url: The sip_url - :returns: Newly created OriginationUrlInstance - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'Weight': weight, - 'Priority': priority, - 'Enabled': enabled, - 'FriendlyName': friendly_name, - 'SipUrl': sip_url, - }) + return self._proxy.delete() - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OriginationUrlInstance - return OriginationUrlInstance(self._version, payload, trunk_sid=self._solution['trunk_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + return await self._proxy.delete_async() - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlInstance] + def fetch(self) -> "OriginationUrlInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the OriginationUrlInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: The fetched OriginationUrlInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the OriginationUrlInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlInstance] + :returns: The fetched OriginationUrlInstance """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + 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": """ - Retrieve a single page of OriginationUrlInstance records from the API. - Request is executed immediately + Update the OriginationUrlInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + :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: Page of OriginationUrlInstance - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlPage + :returns: The updated OriginationUrlInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, + return self._proxy.update( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, ) - return OriginationUrlPage(self._version, response, self._solution) - - def get_page(self, target_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": """ - Retrieve a specific page of OriginationUrlInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the OriginationUrlInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of OriginationUrlInstance - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlPage + :returns: The updated OriginationUrlInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, ) - return OriginationUrlPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a OriginationUrlContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - :param sid: The sid +class OriginationUrlContext(InstanceContext): - :returns: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlContext - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlContext + def __init__(self, version: Version, trunk_sid: str, sid: str): """ - return OriginationUrlContext(self._version, trunk_sid=self._solution['trunk_sid'], sid=sid, ) + Initialize the OriginationUrlContext - def __call__(self, sid): + :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. """ - Constructs a OriginationUrlContext + super().__init__(version) - :param sid: The sid + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid, + } + self._uri = "/Trunks/{trunk_sid}/OriginationUrls/{sid}".format(**self._solution) - :returns: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlContext - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlContext + def delete(self) -> bool: """ - return OriginationUrlContext(self._version, trunk_sid=self._solution['trunk_sid'], sid=sid, ) + Deletes the OriginationUrlInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class OriginationUrlPage(Page): - """ """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, response, solution): + async def delete_async(self) -> bool: """ - Initialize the OriginationUrlPage + Asynchronous coroutine that deletes the OriginationUrlInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param trunk_sid: The trunk_sid - :returns: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlPage - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlPage + :returns: True if delete succeeds, False otherwise """ - super(OriginationUrlPage, self).__init__(version, response) - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of OriginationUrlInstance + headers = values.of({}) - :param dict payload: Payload response from the API + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlInstance - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlInstance + def fetch(self) -> OriginationUrlInstance: """ - return OriginationUrlInstance(self._version, payload, trunk_sid=self._solution['trunk_sid'], ) + Fetch the OriginationUrlInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: The fetched OriginationUrlInstance """ - return '' + headers = values.of({}) -class OriginationUrlContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, trunk_sid, sid): - """ - Initialize the OriginationUrlContext + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :param Version version: Version that contains the resource - :param trunk_sid: The trunk_sid - :param sid: The sid + return OriginationUrlInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlContext - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlContext + async def fetch_async(self) -> OriginationUrlInstance: """ - super(OriginationUrlContext, self).__init__(version) + Asynchronous coroutine to fetch the OriginationUrlInstance - # Path Solution - self._solution = {'trunk_sid': trunk_sid, 'sid': sid, } - self._uri = '/Trunks/{trunk_sid}/OriginationUrls/{sid}'.format(**self._solution) - def fetch(self): + :returns: The fetched OriginationUrlInstance """ - Fetch a OriginationUrlInstance - :returns: Fetched OriginationUrlInstance - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlInstance - """ - params = values.of({}) + headers = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], ) - def delete(self): + 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: """ - Deletes the OriginationUrlInstance + Update the OriginationUrlInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) + :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. - def update(self, weight=values.unset, priority=values.unset, - enabled=values.unset, friendly_name=values.unset, - sip_url=values.unset): + :returns: The updated OriginationUrlInstance """ - Update the OriginationUrlInstance - :param unicode weight: The weight - :param unicode priority: The priority - :param bool enabled: The enabled - :param unicode friendly_name: The friendly_name - :param unicode sip_url: The sip_url + data = values.of( + { + "Weight": weight, + "Priority": priority, + "Enabled": serialize.boolean_to_string(enabled), + "FriendlyName": friendly_name, + "SipUrl": sip_url, + } + ) + headers = values.of({}) - :returns: Updated OriginationUrlInstance - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlInstance - """ - data = values.of({ - 'Weight': weight, - 'Priority': priority, - 'Enabled': enabled, - 'FriendlyName': friendly_name, - 'SipUrl': sip_url, - }) + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" payload = self._version.update( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) return OriginationUrlInstance( self._version, payload, - trunk_sid=self._solution['trunk_sid'], - sid=self._solution['sid'], + 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" - def __repr__(self): + 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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class OriginationUrlInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, trunk_sid, sid=None): - """ - Initialize the OriginationUrlInstance - - :returns: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlInstance - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlInstance - """ - super(OriginationUrlInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'sid': payload['sid'], - 'trunk_sid': payload['trunk_sid'], - 'weight': deserialize.integer(payload['weight']), - 'enabled': payload['enabled'], - 'sip_url': payload['sip_url'], - 'friendly_name': payload['friendly_name'], - 'priority': deserialize.integer(payload['priority']), - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = {'trunk_sid': trunk_sid, 'sid': sid or self._properties['sid'], } +class OriginationUrlPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> OriginationUrlInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of OriginationUrlInstance - :returns: OriginationUrlContext for this OriginationUrlInstance - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = OriginationUrlContext( - self._version, - trunk_sid=self._solution['trunk_sid'], - sid=self._solution['sid'], - ) - return self._context + return OriginationUrlInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['sid'] + return "" - @property - def trunk_sid(self): - """ - :returns: The trunk_sid - :rtype: unicode - """ - return self._properties['trunk_sid'] - @property - def weight(self): - """ - :returns: The weight - :rtype: unicode +class OriginationUrlList(ListResource): + + def __init__(self, version: Version, trunk_sid: str): """ - return self._properties['weight'] + Initialize the OriginationUrlList + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to read the OriginationUrl. - @property - def enabled(self): """ - :returns: The enabled - :rtype: bool + 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]: """ - return self._properties['enabled'] + 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. - @property - def sip_url(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The sip_url - :rtype: unicode + 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]: """ - return self._properties['sip_url'] + 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. - @property - def friendly_name(self): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - :returns: The friendly_name - :rtype: unicode + 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]: """ - return self._properties['friendly_name'] + Lists OriginationUrlInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def priority(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The priority - :rtype: unicode + 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]: """ - return self._properties['priority'] + 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. - @property - def date_created(self): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - :returns: The date_created - :rtype: datetime + 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: """ - return self._properties['date_created'] + Retrieve a single page of OriginationUrlInstance records from the API. + Request is executed immediately - @property - def date_updated(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The date_updated - :rtype: datetime + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page of OriginationUrlInstance records from the API. + Request is executed immediately - @property - def url(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The url - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of OriginationUrlInstance """ - Fetch a OriginationUrlInstance + response = self._version.domain.twilio.request("GET", target_url) + return OriginationUrlPage(self._version, response, self._solution) - :returns: Fetched OriginationUrlInstance - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlInstance + async def get_page_async(self, target_url: str) -> OriginationUrlPage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of OriginationUrlInstance records from the API. + Request is executed immediately - def delete(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of OriginationUrlInstance """ - Deletes the OriginationUrlInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return OriginationUrlPage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def get(self, sid: str) -> OriginationUrlContext: """ - return self._proxy.delete() + Constructs a OriginationUrlContext - def update(self, weight=values.unset, priority=values.unset, - enabled=values.unset, friendly_name=values.unset, - sip_url=values.unset): + :param sid: The unique string that we created to identify the OriginationUrl resource to update. """ - Update the OriginationUrlInstance + return OriginationUrlContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) - :param unicode weight: The weight - :param unicode priority: The priority - :param bool enabled: The enabled - :param unicode friendly_name: The friendly_name - :param unicode sip_url: The sip_url + def __call__(self, sid: str) -> OriginationUrlContext: + """ + Constructs a OriginationUrlContext - :returns: Updated OriginationUrlInstance - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlInstance + :param sid: The unique string that we created to identify the OriginationUrl resource to update. """ - return self._proxy.update( - weight=weight, - priority=priority, - enabled=enabled, - friendly_name=friendly_name, - sip_url=sip_url, + return OriginationUrlContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/trunking/v1/trunk/phone_number.py b/twilio/rest/trunking/v1/trunk/phone_number.py index f71c319545..a7c3dbe20d 100644 --- a/twilio/rest/trunking/v1/trunk/phone_number.py +++ b/twilio/rest/trunking/v1/trunk/phone_number.py @@ -1,573 +1,589 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 PhoneNumberList(ListResource): - """ """ +class PhoneNumberInstance(InstanceResource): - def __init__(self, version, trunk_sid): - """ - Initialize the PhoneNumberList + class AddressRequirement(object): + NONE = "none" + ANY = "any" + LOCAL = "local" + FOREIGN = "foreign" - :param Version version: Version that contains the resource - :param trunk_sid: The trunk_sid + """ + :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 - :returns: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberList - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberList + @property + def _proxy(self) -> "PhoneNumberContext": """ - super(PhoneNumberList, self).__init__(version) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - # Path Solution - self._solution = {'trunk_sid': trunk_sid, } - self._uri = '/Trunks/{trunk_sid}/PhoneNumbers'.format(**self._solution) + :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 create(self, phone_number_sid): + def delete(self) -> bool: """ - Create a new PhoneNumberInstance + Deletes the PhoneNumberInstance - :param unicode phone_number_sid: The phone_number_sid - :returns: Newly created PhoneNumberInstance - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberInstance + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: """ - data = values.of({'PhoneNumberSid': phone_number_sid, }) + Asynchronous coroutine that deletes the PhoneNumberInstance - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - return PhoneNumberInstance(self._version, payload, trunk_sid=self._solution['trunk_sid'], ) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def stream(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the PhoneNumberInstance - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberInstance] + :returns: The fetched PhoneNumberInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(page_size=limits['page_size'], ) + async def fetch_async(self) -> "PhoneNumberInstance": + """ + Asynchronous coroutine to fetch the PhoneNumberInstance - return self._version.stream(page, limits['limit'], limits['page_limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + return await self._proxy.fetch_async() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberInstance] + def __repr__(self) -> str: """ - return list(self.stream(limit=limit, page_size=page_size, )) + Provide a friendly representation - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + :returns: Machine friendly representation """ - Retrieve a single page of PhoneNumberInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of PhoneNumberInstance - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberPage +class PhoneNumberContext(InstanceContext): + + def __init__(self, version: Version, trunk_sid: str, sid: str): """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the PhoneNumberContext - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + :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) - return PhoneNumberPage(self._version, response, self._solution) + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid, + } + self._uri = "/Trunks/{trunk_sid}/PhoneNumbers/{sid}".format(**self._solution) - def get_page(self, target_url): + def delete(self) -> bool: """ - Retrieve a specific page of PhoneNumberInstance records from the API. - Request is executed immediately + Deletes the PhoneNumberInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of PhoneNumberInstance - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberPage + :returns: True if delete succeeds, False otherwise """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return PhoneNumberPage(self._version, response, self._solution) + headers = values.of({}) - def get(self, sid): + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Constructs a PhoneNumberContext + Asynchronous coroutine that deletes the PhoneNumberInstance - :param sid: The sid - :returns: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberContext - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberContext + :returns: True if delete succeeds, False otherwise """ - return PhoneNumberContext(self._version, trunk_sid=self._solution['trunk_sid'], sid=sid, ) - def __call__(self, sid): + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> PhoneNumberInstance: """ - Constructs a PhoneNumberContext + Fetch the PhoneNumberInstance - :param sid: The sid - :returns: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberContext - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberContext + :returns: The fetched PhoneNumberInstance """ - return PhoneNumberContext(self._version, trunk_sid=self._solution['trunk_sid'], sid=sid, ) - def __repr__(self): + 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: """ - Provide a friendly representation + Asynchronous coroutine to fetch the PhoneNumberInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched PhoneNumberInstance """ - return '' + headers = values.of({}) -class PhoneNumberPage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): - """ - Initialize the PhoneNumberPage + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param trunk_sid: The trunk_sid + return PhoneNumberInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberPage - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberPage + def __repr__(self) -> str: """ - super(PhoneNumberPage, self).__init__(version, response) + Provide a friendly representation - # Path Solution - self._solution = solution + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PhoneNumberPage(Page): - def get_instance(self, payload): + def get_instance(self, payload: Dict[str, Any]) -> PhoneNumberInstance: """ Build an instance of PhoneNumberInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberInstance - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberInstance + :param payload: Payload response from the API """ - return PhoneNumberInstance(self._version, payload, trunk_sid=self._solution['trunk_sid'], ) + return PhoneNumberInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class PhoneNumberContext(InstanceContext): - """ """ +class PhoneNumberList(ListResource): - def __init__(self, version, trunk_sid, sid): + def __init__(self, version: Version, trunk_sid: str): """ - Initialize the PhoneNumberContext + Initialize the PhoneNumberList - :param Version version: Version that contains the resource - :param trunk_sid: The trunk_sid - :param sid: The sid + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to read the PhoneNumber resources. - :returns: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberContext - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberContext """ - super(PhoneNumberContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'trunk_sid': trunk_sid, 'sid': sid, } - self._uri = '/Trunks/{trunk_sid}/PhoneNumbers/{sid}'.format(**self._solution) + self._solution = { + "trunk_sid": trunk_sid, + } + self._uri = "/Trunks/{trunk_sid}/PhoneNumbers".format(**self._solution) - def fetch(self): + def create(self, phone_number_sid: str) -> PhoneNumberInstance: """ - Fetch a PhoneNumberInstance + Create the PhoneNumberInstance - :returns: Fetched PhoneNumberInstance - :rtype: twilio.rest.trunking.v1.trunk.phone_number.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 """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + data = values.of( + { + "PhoneNumberSid": phone_number_sid, + } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - return PhoneNumberInstance( - self._version, - payload, - trunk_sid=self._solution['trunk_sid'], - sid=self._solution['sid'], + 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 ) - def delete(self): - """ - Deletes the PhoneNumberInstance + return PhoneNumberInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def create_async(self, phone_number_sid: str) -> PhoneNumberInstance: """ - return self._version.delete('delete', self._uri) + Asynchronously create the PhoneNumberInstance - def __repr__(self): - """ - Provide a friendly representation + :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: Machine friendly representation - :rtype: str + :returns: The created PhoneNumberInstance """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + data = values.of( + { + "PhoneNumberSid": phone_number_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) -class PhoneNumberInstance(InstanceResource): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - class AddressRequirement(object): - NONE = "none" - ANY = "any" - LOCAL = "local" - FOREIGN = "foreign" + headers["Accept"] = "application/json" - def __init__(self, version, payload, trunk_sid, sid=None): - """ - Initialize the PhoneNumberInstance - - :returns: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberInstance - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberInstance - """ - super(PhoneNumberInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'address_requirements': payload['address_requirements'], - 'api_version': payload['api_version'], - 'beta': payload['beta'], - 'capabilities': payload['capabilities'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'friendly_name': payload['friendly_name'], - 'links': payload['links'], - 'phone_number': payload['phone_number'], - 'sid': payload['sid'], - 'sms_application_sid': payload['sms_application_sid'], - 'sms_fallback_method': payload['sms_fallback_method'], - 'sms_fallback_url': payload['sms_fallback_url'], - 'sms_method': payload['sms_method'], - 'sms_url': payload['sms_url'], - 'status_callback': payload['status_callback'], - 'status_callback_method': payload['status_callback_method'], - 'trunk_sid': payload['trunk_sid'], - 'url': payload['url'], - 'voice_application_sid': payload['voice_application_sid'], - 'voice_caller_id_lookup': payload['voice_caller_id_lookup'], - 'voice_fallback_method': payload['voice_fallback_method'], - 'voice_fallback_url': payload['voice_fallback_url'], - 'voice_method': payload['voice_method'], - 'voice_url': payload['voice_url'], - } + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - # Context - self._context = None - self._solution = {'trunk_sid': trunk_sid, 'sid': sid or self._properties['sid'], } + return PhoneNumberInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) - @property - def _proxy(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PhoneNumberInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: PhoneNumberContext for this PhoneNumberInstance - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberContext - """ - if self._context is None: - self._context = PhoneNumberContext( - self._version, - trunk_sid=self._solution['trunk_sid'], - sid=self._solution['sid'], - ) - return self._context + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['account_sid'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def address_requirements(self): - """ - :returns: The address_requirements - :rtype: PhoneNumberInstance.AddressRequirement - """ - return self._properties['address_requirements'] + return self._version.stream(page, limits["limit"]) - @property - def api_version(self): - """ - :returns: The api_version - :rtype: unicode + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PhoneNumberInstance]: """ - return self._properties['api_version'] + 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. - @property - def beta(self): - """ - :returns: The beta - :rtype: bool - """ - return self._properties['beta'] + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - @property - def capabilities(self): - """ - :returns: The capabilities - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['capabilities'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + return self._version.stream_async(page, limits["limit"]) - @property - def date_updated(self): + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PhoneNumberInstance]: """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] + Lists PhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['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) - @property - def links(self): + :returns: list that will contain up to limit results """ - :returns: The links - :rtype: unicode - """ - return self._properties['links'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def phone_number(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PhoneNumberInstance]: """ - :returns: The phone_number - :rtype: unicode - """ - return self._properties['phone_number'] + 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. - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['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) - @property - def sms_application_sid(self): - """ - :returns: The sms_application_sid - :rtype: unicode + :returns: list that will contain up to limit results """ - return self._properties['sms_application_sid'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def sms_fallback_method(self): + 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: """ - :returns: The sms_fallback_method - :rtype: unicode - """ - return self._properties['sms_fallback_method'] + Retrieve a single page of PhoneNumberInstance records from the API. + Request is executed immediately - @property - def sms_fallback_url(self): - """ - :returns: The sms_fallback_url - :rtype: unicode - """ - return self._properties['sms_fallback_url'] + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - @property - def sms_method(self): - """ - :returns: The sms_method - :rtype: unicode + :returns: Page of PhoneNumberInstance """ - return self._properties['sms_method'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def sms_url(self): - """ - :returns: The sms_url - :rtype: unicode - """ - return self._properties['sms_url'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def status_callback(self): - """ - :returns: The status_callback - :rtype: unicode - """ - return self._properties['status_callback'] + headers["Accept"] = "application/json" - @property - def status_callback_method(self): - """ - :returns: The status_callback_method - :rtype: unicode - """ - return self._properties['status_callback_method'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PhoneNumberPage(self._version, response, self._solution) - @property - def trunk_sid(self): - """ - :returns: The trunk_sid - :rtype: unicode + 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: """ - return self._properties['trunk_sid'] + Asynchronously retrieve a single page of PhoneNumberInstance records from the API. + Request is executed immediately - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - @property - def voice_application_sid(self): - """ - :returns: The voice_application_sid - :rtype: unicode + :returns: Page of PhoneNumberInstance """ - return self._properties['voice_application_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def voice_caller_id_lookup(self): - """ - :returns: The voice_caller_id_lookup - :rtype: bool - """ - return self._properties['voice_caller_id_lookup'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def voice_fallback_method(self): - """ - :returns: The voice_fallback_method - :rtype: unicode - """ - return self._properties['voice_fallback_method'] + headers["Accept"] = "application/json" - @property - def voice_fallback_url(self): - """ - :returns: The voice_fallback_url - :rtype: unicode - """ - return self._properties['voice_fallback_url'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PhoneNumberPage(self._version, response, self._solution) - @property - def voice_method(self): + def get_page(self, target_url: str) -> PhoneNumberPage: """ - :returns: The voice_method - :rtype: unicode + 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 """ - return self._properties['voice_method'] + response = self._version.domain.twilio.request("GET", target_url) + return PhoneNumberPage(self._version, response, self._solution) - @property - def voice_url(self): + async def get_page_async(self, target_url: str) -> PhoneNumberPage: """ - :returns: The voice_url - :rtype: unicode + 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 """ - return self._properties['voice_url'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return PhoneNumberPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> PhoneNumberContext: """ - Fetch a PhoneNumberInstance + Constructs a PhoneNumberContext - :returns: Fetched PhoneNumberInstance - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberInstance + :param sid: The unique string that we created to identify the PhoneNumber resource to fetch. """ - return self._proxy.fetch() + return PhoneNumberContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) - def delete(self): + def __call__(self, sid: str) -> PhoneNumberContext: """ - Deletes the PhoneNumberInstance + Constructs a PhoneNumberContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The unique string that we created to identify the PhoneNumber resource to fetch. """ - return self._proxy.delete() + return PhoneNumberContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 "".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 "".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 "" 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 "" 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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" 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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 ( + "".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 ( + "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "" 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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" 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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "" + + +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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "" + + +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 "" + + +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 "" 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 "" diff --git a/twilio/rest/video/__init__.py b/twilio/rest/video/__init__.py index 35a9261e90..d57e4f1ecc 100644 --- a/twilio/rest/video/__init__.py +++ b/twilio/rest/video/__init__.py @@ -1,67 +1,65 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" +from warnings import warn -from twilio.base.domain import Domain -from twilio.rest.video.v1 import V1 +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(Domain): - - def __init__(self, twilio): - """ - Initialize the Video Domain - - :returns: Domain for Video - :rtype: twilio.rest.video.Video - """ - super(Video, self).__init__(twilio) - - self.base_url = 'https://video.twilio.com' - - # Versions - self._v1 = None +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 v1(self): - """ - :returns: Version v1 of video - :rtype: twilio.rest.video.v1.V1 - """ - if self._v1 is None: - self._v1 = V1(self) - return self._v1 + 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 compositions(self): - """ - :rtype: twilio.rest.video.v1.composition.CompositionList - """ - return self.v1.compositions + 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): - """ - :rtype: twilio.rest.video.v1.recording.RecordingList - """ + def recordings(self) -> RecordingList: + warn( + "recordings is deprecated. Use v1.recordings instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v1.recordings @property - def rooms(self): - """ - :rtype: twilio.rest.video.v1.room.RoomList - """ - return self.v1.rooms - - def __repr__(self): - """ - Provide a friendly representation + def recording_settings(self) -> RecordingSettingsList: + warn( + "recording_settings is deprecated. Use v1.recording_settings instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.recording_settings - :returns: Machine friendly representation - :rtype: str - """ - return '' + @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 index 0925ebfb25..0667596a3f 100644 --- a/twilio/rest/video/v1/__init__.py +++ b/twilio/rest/video/v1/__init__.py @@ -1,64 +1,83 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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): + def __init__(self, domain: Domain): """ Initialize the V1 version of Video - :returns: V1 version of Video - :rtype: twilio.rest.video.v1.V1.V1 + :param domain: The Twilio.video domain """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._compositions = None - self._recordings = None - self._rooms = None + 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): - """ - :rtype: twilio.rest.video.v1.composition.CompositionList - """ + def compositions(self) -> CompositionList: if self._compositions is None: self._compositions = CompositionList(self) return self._compositions @property - def recordings(self): - """ - :rtype: twilio.rest.video.v1.recording.RecordingList - """ + 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 rooms(self): - """ - :rtype: twilio.rest.video.v1.room.RoomList - """ + 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): + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :rtype: str """ - return '' + return "" 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 "".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 "".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 "" + + +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 "" diff --git a/twilio/rest/video/v1/composition/__init__.py b/twilio/rest/video/v1/composition/__init__.py deleted file mode 100644 index facf119953..0000000000 --- a/twilio/rest/video/v1/composition/__init__.py +++ /dev/null @@ -1,569 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import serialize -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.page import Page - - -class CompositionList(ListResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version): - """ - Initialize the CompositionList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.video.v1.composition.CompositionList - :rtype: twilio.rest.video.v1.composition.CompositionList - """ - super(CompositionList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Compositions'.format(**self._solution) - - def stream(self, status=values.unset, date_created_after=values.unset, - date_created_before=values.unset, room_sid=values.unset, limit=None, - page_size=None): - """ - 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: The status - :param datetime date_created_after: The date_created_after - :param datetime date_created_before: The date_created_before - :param unicode room_sid: The room_sid - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.video.v1.composition.CompositionInstance] - """ - 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'], limits['page_limit']) - - def list(self, status=values.unset, date_created_after=values.unset, - date_created_before=values.unset, room_sid=values.unset, limit=None, - page_size=None): - """ - 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: The status - :param datetime date_created_after: The date_created_after - :param datetime date_created_before: The date_created_before - :param unicode room_sid: The room_sid - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.video.v1.composition.CompositionInstance] - """ - 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, - )) - - def page(self, status=values.unset, date_created_after=values.unset, - date_created_before=values.unset, room_sid=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of CompositionInstance records from the API. - Request is executed immediately - - :param CompositionInstance.Status status: The status - :param datetime date_created_after: The date_created_after - :param datetime date_created_before: The date_created_before - :param unicode room_sid: The room_sid - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of CompositionInstance - :rtype: twilio.rest.video.v1.composition.CompositionPage - """ - params = 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, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return CompositionPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of CompositionInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of CompositionInstance - :rtype: twilio.rest.video.v1.composition.CompositionPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return CompositionPage(self._version, response, self._solution) - - def create(self, audio_sources=values.unset, video_sources=values.unset, - video_layout=values.unset, resolution=values.unset, - format=values.unset, desired_bitrate=values.unset, - desired_max_duration=values.unset, status_callback=values.unset, - status_callback_method=values.unset, trim=values.unset, - reuse=values.unset): - """ - Create a new CompositionInstance - - :param unicode audio_sources: The audio_sources - :param unicode video_sources: The video_sources - :param CompositionInstance.VideoLayout video_layout: The video_layout - :param unicode resolution: The resolution - :param CompositionInstance.Format format: The format - :param unicode desired_bitrate: The desired_bitrate - :param unicode desired_max_duration: The desired_max_duration - :param unicode status_callback: The status_callback - :param unicode status_callback_method: The status_callback_method - :param bool trim: The trim - :param bool reuse: The reuse - - :returns: Newly created CompositionInstance - :rtype: twilio.rest.video.v1.composition.CompositionInstance - """ - data = values.of({ - 'AudioSources': serialize.map(audio_sources, lambda e: e), - 'VideoSources': serialize.map(video_sources, lambda e: e), - 'VideoLayout': video_layout, - 'Resolution': resolution, - 'Format': format, - 'DesiredBitrate': desired_bitrate, - 'DesiredMaxDuration': desired_max_duration, - 'StatusCallback': status_callback, - 'StatusCallbackMethod': status_callback_method, - 'Trim': trim, - 'Reuse': reuse, - }) - - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return CompositionInstance(self._version, payload, ) - - def get(self, sid): - """ - Constructs a CompositionContext - - :param sid: The sid - - :returns: twilio.rest.video.v1.composition.CompositionContext - :rtype: twilio.rest.video.v1.composition.CompositionContext - """ - return CompositionContext(self._version, sid=sid, ) - - def __call__(self, sid): - """ - Constructs a CompositionContext - - :param sid: The sid - - :returns: twilio.rest.video.v1.composition.CompositionContext - :rtype: twilio.rest.video.v1.composition.CompositionContext - """ - return CompositionContext(self._version, sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class CompositionPage(Page): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, response, solution): - """ - Initialize the CompositionPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.video.v1.composition.CompositionPage - :rtype: twilio.rest.video.v1.composition.CompositionPage - """ - super(CompositionPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of CompositionInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.video.v1.composition.CompositionInstance - :rtype: twilio.rest.video.v1.composition.CompositionInstance - """ - return CompositionInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class CompositionContext(InstanceContext): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - def __init__(self, version, sid): - """ - Initialize the CompositionContext - - :param Version version: Version that contains the resource - :param sid: The sid - - :returns: twilio.rest.video.v1.composition.CompositionContext - :rtype: twilio.rest.video.v1.composition.CompositionContext - """ - super(CompositionContext, self).__init__(version) - - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Compositions/{sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch a CompositionInstance - - :returns: Fetched CompositionInstance - :rtype: twilio.rest.video.v1.composition.CompositionInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return CompositionInstance(self._version, payload, sid=self._solution['sid'], ) - - def delete(self): - """ - Deletes the CompositionInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class CompositionInstance(InstanceResource): - """ PLEASE NOTE that this class contains preview products that are subject - to change. Use them with caution. If you currently do not have developer - preview access, please contact help@twilio.com. """ - - class Status(object): - PROCESSING = "processing" - COMPLETED = "completed" - DELETED = "deleted" - FAILED = "failed" - - class Format(object): - MKA = "mka" - MP3 = "mp3" - M4A = "m4a" - MKV = "mkv" - MP4 = "mp4" - WEBM = "webm" - - class VideoLayout(object): - GRID = "grid" - SINGLE = "single" - PIP = "pip" - SEQUENCE = "sequence" - - def __init__(self, version, payload, sid=None): - """ - Initialize the CompositionInstance - - :returns: twilio.rest.video.v1.composition.CompositionInstance - :rtype: twilio.rest.video.v1.composition.CompositionInstance - """ - super(CompositionInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'status': payload['status'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_completed': payload['date_completed'], - 'date_deleted': payload['date_deleted'], - 'sid': payload['sid'], - 'audio_sources': payload['audio_sources'], - 'video_sources': payload['video_sources'], - 'video_layout': payload['video_layout'], - 'resolution': payload['resolution'], - 'format': payload['format'], - 'bitrate': deserialize.integer(payload['bitrate']), - 'size': deserialize.integer(payload['size']), - 'duration': deserialize.integer(payload['duration']), - 'url': payload['url'], - 'room_sid': payload['room_sid'], - 'links': payload['links'], - } - - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.video.v1.composition.CompositionContext - """ - if self._context is None: - self._context = CompositionContext(self._version, sid=self._solution['sid'], ) - return self._context - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def status(self): - """ - :returns: The status - :rtype: CompositionInstance.Status - """ - return self._properties['status'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_completed(self): - """ - :returns: The date_completed - :rtype: unicode - """ - return self._properties['date_completed'] - - @property - def date_deleted(self): - """ - :returns: The date_deleted - :rtype: unicode - """ - return self._properties['date_deleted'] - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] - - @property - def audio_sources(self): - """ - :returns: The audio_sources - :rtype: unicode - """ - return self._properties['audio_sources'] - - @property - def video_sources(self): - """ - :returns: The video_sources - :rtype: unicode - """ - return self._properties['video_sources'] - - @property - def video_layout(self): - """ - :returns: The video_layout - :rtype: CompositionInstance.VideoLayout - """ - return self._properties['video_layout'] - - @property - def resolution(self): - """ - :returns: The resolution - :rtype: unicode - """ - return self._properties['resolution'] - - @property - def format(self): - """ - :returns: The format - :rtype: CompositionInstance.Format - """ - return self._properties['format'] - - @property - def bitrate(self): - """ - :returns: The bitrate - :rtype: unicode - """ - return self._properties['bitrate'] - - @property - def size(self): - """ - :returns: The size - :rtype: unicode - """ - return self._properties['size'] - - @property - def duration(self): - """ - :returns: The duration - :rtype: unicode - """ - return self._properties['duration'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def room_sid(self): - """ - :returns: The room_sid - :rtype: unicode - """ - return self._properties['room_sid'] - - @property - def links(self): - """ - :returns: The links - :rtype: unicode - """ - return self._properties['links'] - - def fetch(self): - """ - Fetch a CompositionInstance - - :returns: Fetched CompositionInstance - :rtype: twilio.rest.video.v1.composition.CompositionInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the CompositionInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) 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 "".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 "".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 "" + + +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 "" 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 "" + + +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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" diff --git a/twilio/rest/video/v1/recording/__init__.py b/twilio/rest/video/v1/recording/__init__.py deleted file mode 100644 index 7f3df10e93..0000000000 --- a/twilio/rest/video/v1/recording/__init__.py +++ /dev/null @@ -1,495 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import serialize -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.page import Page - - -class RecordingList(ListResource): - """ """ - - def __init__(self, version): - """ - Initialize the RecordingList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.video.v1.recording.RecordingList - :rtype: twilio.rest.video.v1.recording.RecordingList - """ - super(RecordingList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Recordings'.format(**self._solution) - - def stream(self, status=values.unset, source_sid=values.unset, - grouping_sid=values.unset, date_created_after=values.unset, - date_created_before=values.unset, limit=None, page_size=None): - """ - 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: The status - :param unicode source_sid: The source_sid - :param unicode grouping_sid: The grouping_sid - :param datetime date_created_after: The date_created_after - :param datetime date_created_before: The date_created_before - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.video.v1.recording.RecordingInstance] - """ - 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, - page_size=limits['page_size'], - ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, status=values.unset, source_sid=values.unset, - grouping_sid=values.unset, date_created_after=values.unset, - date_created_before=values.unset, limit=None, page_size=None): - """ - 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: The status - :param unicode source_sid: The source_sid - :param unicode grouping_sid: The grouping_sid - :param datetime date_created_after: The date_created_after - :param datetime date_created_before: The date_created_before - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.video.v1.recording.RecordingInstance] - """ - 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, - limit=limit, - page_size=page_size, - )) - - def page(self, status=values.unset, source_sid=values.unset, - grouping_sid=values.unset, date_created_after=values.unset, - date_created_before=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of RecordingInstance records from the API. - Request is executed immediately - - :param RecordingInstance.Status status: The status - :param unicode source_sid: The source_sid - :param unicode grouping_sid: The grouping_sid - :param datetime date_created_after: The date_created_after - :param datetime date_created_before: The date_created_before - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of RecordingInstance - :rtype: twilio.rest.video.v1.recording.RecordingPage - """ - params = 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), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return RecordingPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of RecordingInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of RecordingInstance - :rtype: twilio.rest.video.v1.recording.RecordingPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return RecordingPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a RecordingContext - - :param sid: The sid - - :returns: twilio.rest.video.v1.recording.RecordingContext - :rtype: twilio.rest.video.v1.recording.RecordingContext - """ - return RecordingContext(self._version, sid=sid, ) - - def __call__(self, sid): - """ - Constructs a RecordingContext - - :param sid: The sid - - :returns: twilio.rest.video.v1.recording.RecordingContext - :rtype: twilio.rest.video.v1.recording.RecordingContext - """ - return RecordingContext(self._version, sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class RecordingPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the RecordingPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.video.v1.recording.RecordingPage - :rtype: twilio.rest.video.v1.recording.RecordingPage - """ - super(RecordingPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of RecordingInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.video.v1.recording.RecordingInstance - :rtype: twilio.rest.video.v1.recording.RecordingInstance - """ - return RecordingInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class RecordingContext(InstanceContext): - """ """ - - def __init__(self, version, sid): - """ - Initialize the RecordingContext - - :param Version version: Version that contains the resource - :param sid: The sid - - :returns: twilio.rest.video.v1.recording.RecordingContext - :rtype: twilio.rest.video.v1.recording.RecordingContext - """ - super(RecordingContext, self).__init__(version) - - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Recordings/{sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch a RecordingInstance - - :returns: Fetched RecordingInstance - :rtype: twilio.rest.video.v1.recording.RecordingInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return RecordingInstance(self._version, payload, sid=self._solution['sid'], ) - - def delete(self): - """ - Deletes the RecordingInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete('delete', self._uri) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class RecordingInstance(InstanceResource): - """ """ - - class Status(object): - PROCESSING = "processing" - COMPLETED = "completed" - DELETED = "deleted" - FAILED = "failed" - - class Type(object): - AUDIO = "audio" - VIDEO = "video" - DATA = "data" - - class Format(object): - MKA = "mka" - MKV = "mkv" - - class Codec(object): - VP8 = "VP8" - H264 = "H264" - OPUS = "OPUS" - PCMU = "PCMU" - - def __init__(self, version, payload, sid=None): - """ - Initialize the RecordingInstance - - :returns: twilio.rest.video.v1.recording.RecordingInstance - :rtype: twilio.rest.video.v1.recording.RecordingInstance - """ - super(RecordingInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'status': payload['status'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'sid': payload['sid'], - 'source_sid': payload['source_sid'], - 'size': payload['size'], - 'url': payload['url'], - 'type': payload['type'], - 'duration': deserialize.integer(payload['duration']), - 'container_format': payload['container_format'], - 'codec': payload['codec'], - 'grouping_sids': payload['grouping_sids'], - 'track_name': payload['track_name'], - 'links': payload['links'], - } - - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.video.v1.recording.RecordingContext - """ - if self._context is None: - self._context = RecordingContext(self._version, sid=self._solution['sid'], ) - return self._context - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def status(self): - """ - :returns: The status - :rtype: RecordingInstance.Status - """ - return self._properties['status'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] - - @property - def source_sid(self): - """ - :returns: The source_sid - :rtype: unicode - """ - return self._properties['source_sid'] - - @property - def size(self): - """ - :returns: The size - :rtype: unicode - """ - return self._properties['size'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def type(self): - """ - :returns: The type - :rtype: RecordingInstance.Type - """ - return self._properties['type'] - - @property - def duration(self): - """ - :returns: The duration - :rtype: unicode - """ - return self._properties['duration'] - - @property - def container_format(self): - """ - :returns: The container_format - :rtype: RecordingInstance.Format - """ - return self._properties['container_format'] - - @property - def codec(self): - """ - :returns: The codec - :rtype: RecordingInstance.Codec - """ - return self._properties['codec'] - - @property - def grouping_sids(self): - """ - :returns: The grouping_sids - :rtype: dict - """ - return self._properties['grouping_sids'] - - @property - def track_name(self): - """ - :returns: The track_name - :rtype: unicode - """ - return self._properties['track_name'] - - @property - def links(self): - """ - :returns: The links - :rtype: unicode - """ - return self._properties['links'] - - def fetch(self): - """ - Fetch a RecordingInstance - - :returns: Fetched RecordingInstance - :rtype: twilio.rest.video.v1.recording.RecordingInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the RecordingInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) 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 "" + + +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 "" + + +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 "" diff --git a/twilio/rest/video/v1/room/__init__.py b/twilio/rest/video/v1/room/__init__.py index e695531c16..d51b8b8711 100644 --- a/twilio/rest/video/v1/room/__init__.py +++ b/twilio/rest/video/v1/room/__init__.py @@ -1,620 +1,867 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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.recording import RoomRecordingList -from twilio.rest.video.v1.room.room_participant import ParticipantList - +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 RoomList(ListResource): - """ """ - def __init__(self, version): - """ - Initialize the RoomList +class RoomInstance(InstanceResource): - :param Version version: Version that contains the resource + class RoomStatus(object): + IN_PROGRESS = "in-progress" + COMPLETED = "completed" + FAILED = "failed" - :returns: twilio.rest.video.v1.room.RoomList - :rtype: twilio.rest.video.v1.room.RoomList - """ - super(RoomList, self).__init__(version) + class RoomType(object): + GO = "go" + PEER_TO_PEER = "peer-to-peer" + GROUP = "group" + GROUP_SMALL = "group-small" - # Path Solution - self._solution = {} - self._uri = '/Rooms'.format(**self._solution) - - def create(self, enable_turn=values.unset, type=values.unset, - unique_name=values.unset, status_callback=values.unset, - status_callback_method=values.unset, max_participants=values.unset, - record_participants_on_connect=values.unset, - video_codecs=values.unset, media_region=values.unset): - """ - Create a new RoomInstance - - :param bool enable_turn: The enable_turn - :param RoomInstance.RoomType type: The type - :param unicode unique_name: The unique_name - :param unicode status_callback: The status_callback - :param unicode status_callback_method: The status_callback_method - :param unicode max_participants: The max_participants - :param bool record_participants_on_connect: The record_participants_on_connect - :param RoomInstance.VideoCodec video_codecs: The video_codecs - :param unicode media_region: The media_region - - :returns: Newly created RoomInstance - :rtype: twilio.rest.video.v1.room.RoomInstance - """ - data = values.of({ - 'EnableTurn': enable_turn, - 'Type': type, - 'UniqueName': unique_name, - 'StatusCallback': status_callback, - 'StatusCallbackMethod': status_callback_method, - 'MaxParticipants': max_participants, - 'RecordParticipantsOnConnect': record_participants_on_connect, - 'VideoCodecs': serialize.map(video_codecs, lambda e: e), - 'MediaRegion': media_region, - }) + class VideoCodec(object): + VP8 = "VP8" + H264 = "H264" - payload = self._version.create( - 'POST', - self._uri, - data=data, + """ + :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") - return RoomInstance(self._version, payload, ) + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[RoomContext] = None - def stream(self, status=values.unset, unique_name=values.unset, - date_created_after=values.unset, date_created_before=values.unset, - limit=None, page_size=None): + @property + def _proxy(self) -> "RoomContext": """ - 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. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param RoomInstance.RoomStatus status: The status - :param unicode unique_name: The unique_name - :param datetime date_created_after: The date_created_after - :param datetime date_created_before: The date_created_before - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :returns: RoomContext for this RoomInstance + """ + if self._context is None: + self._context = RoomContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.video.v1.room.RoomInstance] + def fetch(self) -> "RoomInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the RoomInstance - 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'], limits['page_limit']) + :returns: The fetched RoomInstance + """ + return self._proxy.fetch() - def list(self, status=values.unset, unique_name=values.unset, - date_created_after=values.unset, date_created_before=values.unset, - limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the RoomInstance - :param RoomInstance.RoomStatus status: The status - :param unicode unique_name: The unique_name - :param datetime date_created_after: The date_created_after - :param datetime date_created_before: The date_created_before - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.video.v1.room.RoomInstance] + :returns: The fetched RoomInstance """ - 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, - )) + return await self._proxy.fetch_async() - def page(self, status=values.unset, unique_name=values.unset, - date_created_after=values.unset, date_created_before=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def update(self, status: "RoomInstance.RoomStatus") -> "RoomInstance": """ - Retrieve a single page of RoomInstance records from the API. - Request is executed immediately - - :param RoomInstance.RoomStatus status: The status - :param unicode unique_name: The unique_name - :param datetime date_created_after: The date_created_after - :param datetime date_created_before: The date_created_before - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + Update the RoomInstance - :returns: Page of RoomInstance - :rtype: twilio.rest.video.v1.room.RoomPage - """ - params = 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, - }) + :param status: - response = self._version.page( - 'GET', - self._uri, - params=params, + :returns: The updated RoomInstance + """ + return self._proxy.update( + status=status, ) - return RoomPage(self._version, response, self._solution) - - def get_page(self, target_url): + async def update_async(self, status: "RoomInstance.RoomStatus") -> "RoomInstance": """ - Retrieve a specific page of RoomInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the RoomInstance - :param str target_url: API-generated URL for the requested results page + :param status: - :returns: Page of RoomInstance - :rtype: twilio.rest.video.v1.room.RoomPage + :returns: The updated RoomInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + status=status, ) - return RoomPage(self._version, response, self._solution) - - def get(self, sid): + @property + def participants(self) -> ParticipantList: """ - Constructs a RoomContext - - :param sid: The sid - - :returns: twilio.rest.video.v1.room.RoomContext - :rtype: twilio.rest.video.v1.room.RoomContext + Access the participants """ - return RoomContext(self._version, sid=sid, ) + return self._proxy.participants - def __call__(self, sid): + @property + def recording_rules(self) -> RecordingRulesList: """ - Constructs a RoomContext - - :param sid: The sid + Access the recording_rules + """ + return self._proxy.recording_rules - :returns: twilio.rest.video.v1.room.RoomContext - :rtype: twilio.rest.video.v1.room.RoomContext + @property + def recordings(self) -> RoomRecordingList: """ - return RoomContext(self._version, sid=sid, ) + Access the recordings + """ + return self._proxy.recordings - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class RoomPage(Page): - """ """ +class RoomContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the RoomPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the RoomContext - :returns: twilio.rest.video.v1.room.RoomPage - :rtype: twilio.rest.video.v1.room.RoomPage + :param version: Version that contains the resource + :param sid: The SID of the Room resource to update. """ - super(RoomPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of RoomInstance + self._solution = { + "sid": sid, + } + self._uri = "/Rooms/{sid}".format(**self._solution) - :param dict payload: Payload response from the API + self._participants: Optional[ParticipantList] = None + self._recording_rules: Optional[RecordingRulesList] = None + self._recordings: Optional[RoomRecordingList] = None - :returns: twilio.rest.video.v1.room.RoomInstance - :rtype: twilio.rest.video.v1.room.RoomInstance + def fetch(self) -> RoomInstance: """ - return RoomInstance(self._version, payload, ) + Fetch the RoomInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: The fetched RoomInstance """ - return '' + headers = values.of({}) -class RoomContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, sid): - """ - Initialize the RoomContext + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :param Version version: Version that contains the resource - :param sid: The sid + return RoomInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - :returns: twilio.rest.video.v1.room.RoomContext - :rtype: twilio.rest.video.v1.room.RoomContext + async def fetch_async(self) -> RoomInstance: """ - super(RoomContext, self).__init__(version) - - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Rooms/{sid}'.format(**self._solution) + Asynchronous coroutine to fetch the RoomInstance - # Dependents - self._recordings = None - self._participants = None - def fetch(self): + :returns: The fetched RoomInstance """ - Fetch a RoomInstance - :returns: Fetched RoomInstance - :rtype: twilio.rest.video.v1.room.RoomInstance - """ - params = values.of({}) + headers = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], ) + return RoomInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def update(self, status): + def update(self, status: "RoomInstance.RoomStatus") -> RoomInstance: """ Update the RoomInstance - :param RoomInstance.RoomStatus status: The status + :param status: - :returns: Updated RoomInstance - :rtype: twilio.rest.video.v1.room.RoomInstance + :returns: The updated RoomInstance """ - data = values.of({'Status': status, }) - payload = self._version.update( - 'POST', - self._uri, - data=data, + data = values.of( + { + "Status": status, + } ) + headers = values.of({}) - return RoomInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def recordings(self): - """ - Access the recordings + headers["Accept"] = "application/json" - :returns: twilio.rest.video.v1.room.recording.RoomRecordingList - :rtype: twilio.rest.video.v1.room.recording.RoomRecordingList - """ - if self._recordings is None: - self._recordings = RoomRecordingList(self._version, room_sid=self._solution['sid'], ) - return self._recordings + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def participants(self): - """ - Access the participants + return RoomInstance(self._version, payload, sid=self._solution["sid"]) - :returns: twilio.rest.video.v1.room.room_participant.ParticipantList - :rtype: twilio.rest.video.v1.room.room_participant.ParticipantList + async def update_async(self, status: "RoomInstance.RoomStatus") -> RoomInstance: """ - if self._participants is None: - self._participants = ParticipantList(self._version, room_sid=self._solution['sid'], ) - return self._participants + Asynchronous coroutine to update the RoomInstance - def __repr__(self): - """ - Provide a friendly representation + :param status: - :returns: Machine friendly representation - :rtype: str + :returns: The updated RoomInstance """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class RoomInstance(InstanceResource): - """ """ - class RoomStatus(object): - IN_PROGRESS = "in-progress" - COMPLETED = "completed" - FAILED = "failed" + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) - class RoomType(object): - PEER_TO_PEER = "peer-to-peer" - GROUP = "group" + headers["Content-Type"] = "application/x-www-form-urlencoded" - class VideoCodec(object): - VP8 = "VP8" - H264 = "H264" + headers["Accept"] = "application/json" - def __init__(self, version, payload, sid=None): - """ - Initialize the RoomInstance - - :returns: twilio.rest.video.v1.room.RoomInstance - :rtype: twilio.rest.video.v1.room.RoomInstance - """ - super(RoomInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'status': payload['status'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'account_sid': payload['account_sid'], - 'enable_turn': payload['enable_turn'], - 'unique_name': payload['unique_name'], - 'status_callback': payload['status_callback'], - 'status_callback_method': payload['status_callback_method'], - 'end_time': deserialize.iso8601_datetime(payload['end_time']), - 'duration': deserialize.integer(payload['duration']), - 'type': payload['type'], - 'max_participants': deserialize.integer(payload['max_participants']), - 'record_participants_on_connect': payload['record_participants_on_connect'], - 'video_codecs': payload['video_codecs'], - 'media_region': payload['media_region'], - 'url': payload['url'], - 'links': payload['links'], - } + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + return RoomInstance(self._version, payload, sid=self._solution["sid"]) @property - def _proxy(self): + def participants(self) -> ParticipantList: """ - 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 - :rtype: twilio.rest.video.v1.room.RoomContext + Access the participants """ - if self._context is None: - self._context = RoomContext(self._version, sid=self._solution['sid'], ) - return self._context + if self._participants is None: + self._participants = ParticipantList( + self._version, + self._solution["sid"], + ) + return self._participants @property - def sid(self): + def recording_rules(self) -> RecordingRulesList: """ - :returns: The sid - :rtype: unicode + Access the recording_rules """ - return self._properties['sid'] + if self._recording_rules is None: + self._recording_rules = RecordingRulesList( + self._version, + self._solution["sid"], + ) + return self._recording_rules @property - def status(self): + def recordings(self) -> RoomRecordingList: """ - :returns: The status - :rtype: RoomInstance.RoomStatus + Access the recordings """ - return self._properties['status'] + if self._recordings is None: + self._recordings = RoomRecordingList( + self._version, + self._solution["sid"], + ) + return self._recordings - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime + def __repr__(self) -> str: """ - return self._properties['date_created'] + Provide a friendly representation - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime + :returns: Machine friendly representation """ - return self._properties['date_updated'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def enable_turn(self): - """ - :returns: The enable_turn - :rtype: bool - """ - return self._properties['enable_turn'] +class RoomPage(Page): - @property - def unique_name(self): - """ - :returns: The unique_name - :rtype: unicode + def get_instance(self, payload: Dict[str, Any]) -> RoomInstance: """ - return self._properties['unique_name'] + Build an instance of RoomInstance - @property - def status_callback(self): + :param payload: Payload response from the API """ - :returns: The status_callback - :rtype: unicode - """ - return self._properties['status_callback'] + return RoomInstance(self._version, payload) - @property - def status_callback_method(self): + def __repr__(self) -> str: """ - :returns: The status_callback_method - :rtype: unicode - """ - return self._properties['status_callback_method'] + Provide a friendly representation - @property - def end_time(self): - """ - :returns: The end_time - :rtype: datetime + :returns: Machine friendly representation """ - return self._properties['end_time'] + return "" - @property - def duration(self): - """ - :returns: The duration - :rtype: unicode - """ - return self._properties['duration'] - @property - def type(self): - """ - :returns: The type - :rtype: RoomInstance.RoomType - """ - return self._properties['type'] +class RoomList(ListResource): - @property - def max_participants(self): + def __init__(self, version: Version): """ - :returns: The max_participants - :rtype: unicode - """ - return self._properties['max_participants'] + Initialize the RoomList - @property - def record_participants_on_connect(self): - """ - :returns: The record_participants_on_connect - :rtype: bool - """ - return self._properties['record_participants_on_connect'] + :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"}) - @property - def video_codecs(self): + 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]: """ - :returns: The video_codecs - :rtype: RoomInstance.VideoCodec + 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 """ - return self._properties['video_codecs'] + 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"], + ) - @property - def media_region(self): + 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]: """ - :returns: The media_region - :rtype: unicode + 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 """ - return self._properties['media_region'] + 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"], + ) - @property - def url(self): + 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]: """ - :returns: The url - :rtype: unicode + 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: """ - return self._properties['url'] + Retrieve a single page of RoomInstance records from the API. + Request is executed immediately - @property - def links(self): + :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 """ - :returns: The links - :rtype: unicode + 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 """ - return self._properties['links'] + 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 fetch(self): + def get_page(self, target_url: str) -> RoomPage: """ - Fetch a RoomInstance + Retrieve a specific page of RoomInstance records from the API. + Request is executed immediately - :returns: Fetched RoomInstance - :rtype: twilio.rest.video.v1.room.RoomInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoomInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return RoomPage(self._version, response) - def update(self, status): + async def get_page_async(self, target_url: str) -> RoomPage: """ - Update the RoomInstance + Asynchronously retrieve a specific page of RoomInstance records from the API. + Request is executed immediately - :param RoomInstance.RoomStatus status: The status + :param target_url: API-generated URL for the requested results page - :returns: Updated RoomInstance - :rtype: twilio.rest.video.v1.room.RoomInstance + :returns: Page of RoomInstance """ - return self._proxy.update(status, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return RoomPage(self._version, response) - @property - def recordings(self): + def get(self, sid: str) -> RoomContext: """ - Access the recordings + Constructs a RoomContext - :returns: twilio.rest.video.v1.room.recording.RoomRecordingList - :rtype: twilio.rest.video.v1.room.recording.RoomRecordingList + :param sid: The SID of the Room resource to update. """ - return self._proxy.recordings + return RoomContext(self._version, sid=sid) - @property - def participants(self): + def __call__(self, sid: str) -> RoomContext: """ - Access the participants + Constructs a RoomContext - :returns: twilio.rest.video.v1.room.room_participant.ParticipantList - :rtype: twilio.rest.video.v1.room.room_participant.ParticipantList + :param sid: The SID of the Room resource to update. """ - return self._proxy.participants + return RoomContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "" 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 "".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 "".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 "" + + +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 "" diff --git a/twilio/rest/video/v1/room/recording/__init__.py b/twilio/rest/video/v1/room/recording/__init__.py deleted file mode 100644 index d88879a17f..0000000000 --- a/twilio/rest/video/v1/room/recording/__init__.py +++ /dev/null @@ -1,483 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import serialize -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.page import Page - - -class RoomRecordingList(ListResource): - """ """ - - def __init__(self, version, room_sid): - """ - Initialize the RoomRecordingList - - :param Version version: Version that contains the resource - :param room_sid: The room_sid - - :returns: twilio.rest.video.v1.room.recording.RoomRecordingList - :rtype: twilio.rest.video.v1.room.recording.RoomRecordingList - """ - super(RoomRecordingList, self).__init__(version) - - # Path Solution - self._solution = {'room_sid': room_sid, } - self._uri = '/Rooms/{room_sid}/Recordings'.format(**self._solution) - - def stream(self, status=values.unset, source_sid=values.unset, - date_created_after=values.unset, date_created_before=values.unset, - limit=None, page_size=None): - """ - 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: The status - :param unicode source_sid: The source_sid - :param datetime date_created_after: The date_created_after - :param datetime date_created_before: The date_created_before - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.video.v1.room.recording.RoomRecordingInstance] - """ - 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'], limits['page_limit']) - - def list(self, status=values.unset, source_sid=values.unset, - date_created_after=values.unset, date_created_before=values.unset, - limit=None, page_size=None): - """ - 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: The status - :param unicode source_sid: The source_sid - :param datetime date_created_after: The date_created_after - :param datetime date_created_before: The date_created_before - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.video.v1.room.recording.RoomRecordingInstance] - """ - 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, - )) - - def page(self, status=values.unset, source_sid=values.unset, - date_created_after=values.unset, date_created_before=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of RoomRecordingInstance records from the API. - Request is executed immediately - - :param RoomRecordingInstance.Status status: The status - :param unicode source_sid: The source_sid - :param datetime date_created_after: The date_created_after - :param datetime date_created_before: The date_created_before - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of RoomRecordingInstance - :rtype: twilio.rest.video.v1.room.recording.RoomRecordingPage - """ - params = 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, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return RoomRecordingPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of RoomRecordingInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of RoomRecordingInstance - :rtype: twilio.rest.video.v1.room.recording.RoomRecordingPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return RoomRecordingPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a RoomRecordingContext - - :param sid: The sid - - :returns: twilio.rest.video.v1.room.recording.RoomRecordingContext - :rtype: twilio.rest.video.v1.room.recording.RoomRecordingContext - """ - return RoomRecordingContext(self._version, room_sid=self._solution['room_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a RoomRecordingContext - - :param sid: The sid - - :returns: twilio.rest.video.v1.room.recording.RoomRecordingContext - :rtype: twilio.rest.video.v1.room.recording.RoomRecordingContext - """ - return RoomRecordingContext(self._version, room_sid=self._solution['room_sid'], sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class RoomRecordingPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the RoomRecordingPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param room_sid: The room_sid - - :returns: twilio.rest.video.v1.room.recording.RoomRecordingPage - :rtype: twilio.rest.video.v1.room.recording.RoomRecordingPage - """ - super(RoomRecordingPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of RoomRecordingInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.video.v1.room.recording.RoomRecordingInstance - :rtype: twilio.rest.video.v1.room.recording.RoomRecordingInstance - """ - return RoomRecordingInstance(self._version, payload, room_sid=self._solution['room_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class RoomRecordingContext(InstanceContext): - """ """ - - def __init__(self, version, room_sid, sid): - """ - Initialize the RoomRecordingContext - - :param Version version: Version that contains the resource - :param room_sid: The room_sid - :param sid: The sid - - :returns: twilio.rest.video.v1.room.recording.RoomRecordingContext - :rtype: twilio.rest.video.v1.room.recording.RoomRecordingContext - """ - super(RoomRecordingContext, self).__init__(version) - - # Path Solution - self._solution = {'room_sid': room_sid, 'sid': sid, } - self._uri = '/Rooms/{room_sid}/Recordings/{sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch a RoomRecordingInstance - - :returns: Fetched RoomRecordingInstance - :rtype: twilio.rest.video.v1.room.recording.RoomRecordingInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return RoomRecordingInstance( - self._version, - payload, - room_sid=self._solution['room_sid'], - sid=self._solution['sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class RoomRecordingInstance(InstanceResource): - """ """ - - class Status(object): - PROCESSING = "processing" - COMPLETED = "completed" - DELETED = "deleted" - FAILED = "failed" - - class Type(object): - AUDIO = "audio" - VIDEO = "video" - DATA = "data" - - class Format(object): - MKA = "mka" - MKV = "mkv" - - class Codec(object): - VP8 = "VP8" - H264 = "H264" - OPUS = "OPUS" - PCMU = "PCMU" - - def __init__(self, version, payload, room_sid, sid=None): - """ - Initialize the RoomRecordingInstance - - :returns: twilio.rest.video.v1.room.recording.RoomRecordingInstance - :rtype: twilio.rest.video.v1.room.recording.RoomRecordingInstance - """ - super(RoomRecordingInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload['account_sid'], - 'status': payload['status'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'sid': payload['sid'], - 'source_sid': payload['source_sid'], - 'size': deserialize.integer(payload['size']), - 'type': payload['type'], - 'duration': deserialize.integer(payload['duration']), - 'container_format': payload['container_format'], - 'codec': payload['codec'], - 'grouping_sids': payload['grouping_sids'], - 'room_sid': payload['room_sid'], - 'url': payload['url'], - 'links': payload['links'], - } - - # Context - self._context = None - self._solution = {'room_sid': room_sid, 'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.video.v1.room.recording.RoomRecordingContext - """ - if self._context is None: - self._context = RoomRecordingContext( - self._version, - room_sid=self._solution['room_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def status(self): - """ - :returns: The status - :rtype: RoomRecordingInstance.Status - """ - return self._properties['status'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] - - @property - def source_sid(self): - """ - :returns: The source_sid - :rtype: unicode - """ - return self._properties['source_sid'] - - @property - def size(self): - """ - :returns: The size - :rtype: unicode - """ - return self._properties['size'] - - @property - def type(self): - """ - :returns: The type - :rtype: RoomRecordingInstance.Type - """ - return self._properties['type'] - - @property - def duration(self): - """ - :returns: The duration - :rtype: unicode - """ - return self._properties['duration'] - - @property - def container_format(self): - """ - :returns: The container_format - :rtype: RoomRecordingInstance.Format - """ - return self._properties['container_format'] - - @property - def codec(self): - """ - :returns: The codec - :rtype: RoomRecordingInstance.Codec - """ - return self._properties['codec'] - - @property - def grouping_sids(self): - """ - :returns: The grouping_sids - :rtype: dict - """ - return self._properties['grouping_sids'] - - @property - def room_sid(self): - """ - :returns: The room_sid - :rtype: unicode - """ - return self._properties['room_sid'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def links(self): - """ - :returns: The links - :rtype: unicode - """ - return self._properties['links'] - - def fetch(self): - """ - Fetch a RoomRecordingInstance - - :returns: Fetched RoomRecordingInstance - :rtype: twilio.rest.video.v1.room.recording.RoomRecordingInstance - """ - return self._proxy.fetch() - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) 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 "".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 "" diff --git a/twilio/rest/video/v1/room/room_participant/__init__.py b/twilio/rest/video/v1/room/room_participant/__init__.py deleted file mode 100644 index aa61889625..0000000000 --- a/twilio/rest/video/v1/room/room_participant/__init__.py +++ /dev/null @@ -1,541 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import serialize -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.page import Page -from twilio.rest.video.v1.room.room_participant.room_participant_published_track import PublishedTrackList -from twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track import SubscribedTrackList - - -class ParticipantList(ListResource): - """ """ - - def __init__(self, version, room_sid): - """ - Initialize the ParticipantList - - :param Version version: Version that contains the resource - :param room_sid: The room_sid - - :returns: twilio.rest.video.v1.room.room_participant.ParticipantList - :rtype: twilio.rest.video.v1.room.room_participant.ParticipantList - """ - super(ParticipantList, self).__init__(version) - - # Path Solution - self._solution = {'room_sid': room_sid, } - self._uri = '/Rooms/{room_sid}/Participants'.format(**self._solution) - - def stream(self, status=values.unset, identity=values.unset, - date_created_after=values.unset, date_created_before=values.unset, - limit=None, page_size=None): - """ - 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: The status - :param unicode identity: The identity - :param datetime date_created_after: The date_created_after - :param datetime date_created_before: The date_created_before - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.video.v1.room.room_participant.ParticipantInstance] - """ - 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'], limits['page_limit']) - - def list(self, status=values.unset, identity=values.unset, - date_created_after=values.unset, date_created_before=values.unset, - limit=None, page_size=None): - """ - 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: The status - :param unicode identity: The identity - :param datetime date_created_after: The date_created_after - :param datetime date_created_before: The date_created_before - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.video.v1.room.room_participant.ParticipantInstance] - """ - 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, - )) - - def page(self, status=values.unset, identity=values.unset, - date_created_after=values.unset, date_created_before=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of ParticipantInstance records from the API. - Request is executed immediately - - :param ParticipantInstance.Status status: The status - :param unicode identity: The identity - :param datetime date_created_after: The date_created_after - :param datetime date_created_before: The date_created_before - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of ParticipantInstance - :rtype: twilio.rest.video.v1.room.room_participant.ParticipantPage - """ - params = 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, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return ParticipantPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of ParticipantInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of ParticipantInstance - :rtype: twilio.rest.video.v1.room.room_participant.ParticipantPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ParticipantPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a ParticipantContext - - :param sid: The sid - - :returns: twilio.rest.video.v1.room.room_participant.ParticipantContext - :rtype: twilio.rest.video.v1.room.room_participant.ParticipantContext - """ - return ParticipantContext(self._version, room_sid=self._solution['room_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a ParticipantContext - - :param sid: The sid - - :returns: twilio.rest.video.v1.room.room_participant.ParticipantContext - :rtype: twilio.rest.video.v1.room.room_participant.ParticipantContext - """ - return ParticipantContext(self._version, room_sid=self._solution['room_sid'], sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ParticipantPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the ParticipantPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param room_sid: The room_sid - - :returns: twilio.rest.video.v1.room.room_participant.ParticipantPage - :rtype: twilio.rest.video.v1.room.room_participant.ParticipantPage - """ - super(ParticipantPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of ParticipantInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.video.v1.room.room_participant.ParticipantInstance - :rtype: twilio.rest.video.v1.room.room_participant.ParticipantInstance - """ - return ParticipantInstance(self._version, payload, room_sid=self._solution['room_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ParticipantContext(InstanceContext): - """ """ - - def __init__(self, version, room_sid, sid): - """ - Initialize the ParticipantContext - - :param Version version: Version that contains the resource - :param room_sid: The room_sid - :param sid: The sid - - :returns: twilio.rest.video.v1.room.room_participant.ParticipantContext - :rtype: twilio.rest.video.v1.room.room_participant.ParticipantContext - """ - super(ParticipantContext, self).__init__(version) - - # Path Solution - self._solution = {'room_sid': room_sid, 'sid': sid, } - self._uri = '/Rooms/{room_sid}/Participants/{sid}'.format(**self._solution) - - # Dependents - self._published_tracks = None - self._subscribed_tracks = None - - def fetch(self): - """ - Fetch a ParticipantInstance - - :returns: Fetched ParticipantInstance - :rtype: twilio.rest.video.v1.room.room_participant.ParticipantInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return ParticipantInstance( - self._version, - payload, - room_sid=self._solution['room_sid'], - sid=self._solution['sid'], - ) - - def update(self, status=values.unset): - """ - Update the ParticipantInstance - - :param ParticipantInstance.Status status: The status - - :returns: Updated ParticipantInstance - :rtype: twilio.rest.video.v1.room.room_participant.ParticipantInstance - """ - data = values.of({'Status': status, }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return ParticipantInstance( - self._version, - payload, - room_sid=self._solution['room_sid'], - sid=self._solution['sid'], - ) - - @property - def published_tracks(self): - """ - Access the published_tracks - - :returns: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackList - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackList - """ - if self._published_tracks is None: - self._published_tracks = PublishedTrackList( - self._version, - room_sid=self._solution['room_sid'], - participant_sid=self._solution['sid'], - ) - return self._published_tracks - - @property - def subscribed_tracks(self): - """ - Access the subscribed_tracks - - :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackList - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackList - """ - if self._subscribed_tracks is None: - self._subscribed_tracks = SubscribedTrackList( - self._version, - room_sid=self._solution['room_sid'], - subscriber_sid=self._solution['sid'], - ) - return self._subscribed_tracks - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class ParticipantInstance(InstanceResource): - """ """ - - class Status(object): - CONNECTED = "connected" - DISCONNECTED = "disconnected" - - def __init__(self, version, payload, room_sid, sid=None): - """ - Initialize the ParticipantInstance - - :returns: twilio.rest.video.v1.room.room_participant.ParticipantInstance - :rtype: twilio.rest.video.v1.room.room_participant.ParticipantInstance - """ - super(ParticipantInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'room_sid': payload['room_sid'], - 'account_sid': payload['account_sid'], - 'status': payload['status'], - 'identity': payload['identity'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'start_time': deserialize.iso8601_datetime(payload['start_time']), - 'end_time': deserialize.iso8601_datetime(payload['end_time']), - 'duration': deserialize.integer(payload['duration']), - 'url': payload['url'], - 'links': payload['links'], - } - - # Context - self._context = None - self._solution = {'room_sid': room_sid, 'sid': sid or self._properties['sid'], } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.video.v1.room.room_participant.ParticipantContext - """ - if self._context is None: - self._context = ParticipantContext( - self._version, - room_sid=self._solution['room_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] - - @property - def room_sid(self): - """ - :returns: The room_sid - :rtype: unicode - """ - return self._properties['room_sid'] - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def status(self): - """ - :returns: The status - :rtype: ParticipantInstance.Status - """ - return self._properties['status'] - - @property - def identity(self): - """ - :returns: The identity - :rtype: unicode - """ - return self._properties['identity'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def start_time(self): - """ - :returns: The start_time - :rtype: datetime - """ - return self._properties['start_time'] - - @property - def end_time(self): - """ - :returns: The end_time - :rtype: datetime - """ - return self._properties['end_time'] - - @property - def duration(self): - """ - :returns: The duration - :rtype: unicode - """ - return self._properties['duration'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def links(self): - """ - :returns: The links - :rtype: unicode - """ - return self._properties['links'] - - def fetch(self): - """ - Fetch a ParticipantInstance - - :returns: Fetched ParticipantInstance - :rtype: twilio.rest.video.v1.room.room_participant.ParticipantInstance - """ - return self._proxy.fetch() - - def update(self, status=values.unset): - """ - Update the ParticipantInstance - - :param ParticipantInstance.Status status: The status - - :returns: Updated ParticipantInstance - :rtype: twilio.rest.video.v1.room.room_participant.ParticipantInstance - """ - return self._proxy.update(status=status, ) - - @property - def published_tracks(self): - """ - Access the published_tracks - - :returns: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackList - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackList - """ - return self._proxy.published_tracks - - @property - def subscribed_tracks(self): - """ - Access the subscribed_tracks - - :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackList - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackList - """ - return self._proxy.subscribed_tracks - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/video/v1/room/room_participant/room_participant_published_track.py b/twilio/rest/video/v1/room/room_participant/room_participant_published_track.py deleted file mode 100644 index 2e07efd8c1..0000000000 --- a/twilio/rest/video/v1/room/room_participant/room_participant_published_track.py +++ /dev/null @@ -1,406 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -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.page import Page - - -class PublishedTrackList(ListResource): - """ """ - - def __init__(self, version, room_sid, participant_sid): - """ - Initialize the PublishedTrackList - - :param Version version: Version that contains the resource - :param room_sid: The room_sid - :param participant_sid: The participant_sid - - :returns: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackList - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackList - """ - super(PublishedTrackList, self).__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=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, limit=None, page_size=None): - """ - 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 int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackInstance] - """ - return list(self.stream(limit=limit, page_size=page_size, )) - - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of PublishedTrackInstance records from the API. - Request is executed immediately - - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of PublishedTrackInstance - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackPage - """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return PublishedTrackPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of PublishedTrackInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of PublishedTrackInstance - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return PublishedTrackPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a PublishedTrackContext - - :param sid: The sid - - :returns: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackContext - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackContext - """ - return PublishedTrackContext( - self._version, - room_sid=self._solution['room_sid'], - participant_sid=self._solution['participant_sid'], - sid=sid, - ) - - def __call__(self, sid): - """ - Constructs a PublishedTrackContext - - :param sid: The sid - - :returns: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackContext - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackContext - """ - return PublishedTrackContext( - self._version, - room_sid=self._solution['room_sid'], - participant_sid=self._solution['participant_sid'], - sid=sid, - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class PublishedTrackPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the PublishedTrackPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param room_sid: The room_sid - :param participant_sid: The participant_sid - - :returns: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackPage - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackPage - """ - super(PublishedTrackPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of PublishedTrackInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackInstance - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackInstance - """ - return PublishedTrackInstance( - self._version, - payload, - room_sid=self._solution['room_sid'], - participant_sid=self._solution['participant_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class PublishedTrackContext(InstanceContext): - """ """ - - def __init__(self, version, room_sid, participant_sid, sid): - """ - Initialize the PublishedTrackContext - - :param Version version: Version that contains the resource - :param room_sid: The room_sid - :param participant_sid: The participant_sid - :param sid: The sid - - :returns: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackContext - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackContext - """ - super(PublishedTrackContext, self).__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): - """ - Fetch a PublishedTrackInstance - - :returns: Fetched PublishedTrackInstance - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackInstance - """ - params = values.of({}) - - payload = self._version.fetch( - 'GET', - self._uri, - params=params, - ) - - return PublishedTrackInstance( - self._version, - payload, - room_sid=self._solution['room_sid'], - participant_sid=self._solution['participant_sid'], - sid=self._solution['sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class PublishedTrackInstance(InstanceResource): - """ """ - - class Kind(object): - AUDIO = "audio" - VIDEO = "video" - DATA = "data" - - def __init__(self, version, payload, room_sid, participant_sid, sid=None): - """ - Initialize the PublishedTrackInstance - - :returns: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackInstance - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackInstance - """ - super(PublishedTrackInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'participant_sid': payload['participant_sid'], - 'room_sid': payload['room_sid'], - 'name': payload['name'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'enabled': payload['enabled'], - 'kind': payload['kind'], - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = { - 'room_sid': room_sid, - 'participant_sid': participant_sid, - 'sid': sid or self._properties['sid'], - } - - @property - def _proxy(self): - """ - 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 - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackContext - """ - 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 - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] - - @property - def participant_sid(self): - """ - :returns: The participant_sid - :rtype: unicode - """ - return self._properties['participant_sid'] - - @property - def room_sid(self): - """ - :returns: The room_sid - :rtype: unicode - """ - return self._properties['room_sid'] - - @property - def name(self): - """ - :returns: The name - :rtype: unicode - """ - return self._properties['name'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def enabled(self): - """ - :returns: The enabled - :rtype: bool - """ - return self._properties['enabled'] - - @property - def kind(self): - """ - :returns: The kind - :rtype: PublishedTrackInstance.Kind - """ - return self._properties['kind'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch a PublishedTrackInstance - - :returns: Fetched PublishedTrackInstance - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackInstance - """ - return self._proxy.fetch() - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) diff --git a/twilio/rest/video/v1/room/room_participant/room_participant_subscribed_track.py b/twilio/rest/video/v1/room/room_participant/room_participant_subscribed_track.py deleted file mode 100644 index 0f21fc2254..0000000000 --- a/twilio/rest/video/v1/room/room_participant/room_participant_subscribed_track.py +++ /dev/null @@ -1,365 +0,0 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.page import Page - - -class SubscribedTrackList(ListResource): - """ """ - - def __init__(self, version, room_sid, subscriber_sid): - """ - Initialize the SubscribedTrackList - - :param Version version: Version that contains the resource - :param room_sid: The room_sid - :param subscriber_sid: The subscriber_sid - - :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackList - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackList - """ - super(SubscribedTrackList, self).__init__(version) - - # Path Solution - self._solution = {'room_sid': room_sid, 'subscriber_sid': subscriber_sid, } - self._uri = '/Rooms/{room_sid}/Participants/{subscriber_sid}/SubscribedTracks'.format(**self._solution) - - def stream(self, date_created_after=values.unset, - date_created_before=values.unset, track=values.unset, - publisher=values.unset, kind=values.unset, limit=None, - page_size=None): - """ - 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 datetime date_created_after: The date_created_after - :param datetime date_created_before: The date_created_before - :param unicode track: The track - :param unicode publisher: The publisher - :param SubscribedTrackInstance.Kind kind: The kind - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page( - date_created_after=date_created_after, - date_created_before=date_created_before, - track=track, - publisher=publisher, - kind=kind, - page_size=limits['page_size'], - ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) - - def list(self, date_created_after=values.unset, - date_created_before=values.unset, track=values.unset, - publisher=values.unset, kind=values.unset, limit=None, page_size=None): - """ - 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 datetime date_created_after: The date_created_after - :param datetime date_created_before: The date_created_before - :param unicode track: The track - :param unicode publisher: The publisher - :param SubscribedTrackInstance.Kind kind: The kind - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackInstance] - """ - return list(self.stream( - date_created_after=date_created_after, - date_created_before=date_created_before, - track=track, - publisher=publisher, - kind=kind, - limit=limit, - page_size=page_size, - )) - - def page(self, date_created_after=values.unset, - date_created_before=values.unset, track=values.unset, - publisher=values.unset, kind=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of SubscribedTrackInstance records from the API. - Request is executed immediately - - :param datetime date_created_after: The date_created_after - :param datetime date_created_before: The date_created_before - :param unicode track: The track - :param unicode publisher: The publisher - :param SubscribedTrackInstance.Kind kind: The kind - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - - :returns: Page of SubscribedTrackInstance - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackPage - """ - params = values.of({ - 'DateCreatedAfter': serialize.iso8601_datetime(date_created_after), - 'DateCreatedBefore': serialize.iso8601_datetime(date_created_before), - 'Track': track, - 'Publisher': publisher, - 'Kind': kind, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return SubscribedTrackPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of SubscribedTrackInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of SubscribedTrackInstance - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return SubscribedTrackPage(self._version, response, self._solution) - - def update(self, track=values.unset, publisher=values.unset, kind=values.unset, - status=values.unset): - """ - Update the SubscribedTrackInstance - - :param unicode track: The track - :param unicode publisher: The publisher - :param SubscribedTrackInstance.Kind kind: The kind - :param SubscribedTrackInstance.Status status: The status - - :returns: Updated SubscribedTrackInstance - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackInstance - """ - data = values.of({'Track': track, 'Publisher': publisher, 'Kind': kind, 'Status': status, }) - - payload = self._version.update( - 'POST', - self._uri, - data=data, - ) - - return SubscribedTrackInstance( - self._version, - payload, - room_sid=self._solution['room_sid'], - subscriber_sid=self._solution['subscriber_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SubscribedTrackPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the SubscribedTrackPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param room_sid: The room_sid - :param subscriber_sid: The subscriber_sid - - :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackPage - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackPage - """ - super(SubscribedTrackPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of SubscribedTrackInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackInstance - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackInstance - """ - return SubscribedTrackInstance( - self._version, - payload, - room_sid=self._solution['room_sid'], - subscriber_sid=self._solution['subscriber_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SubscribedTrackInstance(InstanceResource): - """ """ - - class Kind(object): - AUDIO = "audio" - VIDEO = "video" - DATA = "data" - - class Status(object): - SUBSCRIBE = "subscribe" - UNSUBSCRIBE = "unsubscribe" - - def __init__(self, version, payload, room_sid, subscriber_sid): - """ - Initialize the SubscribedTrackInstance - - :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackInstance - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackInstance - """ - super(SubscribedTrackInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'room_sid': payload['room_sid'], - 'name': payload['name'], - 'publisher_sid': payload['publisher_sid'], - 'subscriber_sid': payload['subscriber_sid'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'enabled': payload['enabled'], - 'kind': payload['kind'], - } - - # Context - self._context = None - self._solution = {'room_sid': room_sid, 'subscriber_sid': subscriber_sid, } - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] - - @property - def room_sid(self): - """ - :returns: The room_sid - :rtype: unicode - """ - return self._properties['room_sid'] - - @property - def name(self): - """ - :returns: The name - :rtype: unicode - """ - return self._properties['name'] - - @property - def publisher_sid(self): - """ - :returns: The publisher_sid - :rtype: unicode - """ - return self._properties['publisher_sid'] - - @property - def subscriber_sid(self): - """ - :returns: The subscriber_sid - :rtype: unicode - """ - return self._properties['subscriber_sid'] - - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def enabled(self): - """ - :returns: The enabled - :rtype: bool - """ - return self._properties['enabled'] - - @property - def kind(self): - """ - :returns: The kind - :rtype: SubscribedTrackInstance.Kind - """ - return self._properties['kind'] - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' 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 "".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 "".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 "" + + +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 "" 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 "" 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 "" 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 "".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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "" 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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "" + + +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 "" 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 "" + + +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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" + + +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 "" 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 "" diff --git a/twilio/rest/wireless/__init__.py b/twilio/rest/wireless/__init__.py index 36f1de3363..3b7a40977c 100644 --- a/twilio/rest/wireless/__init__.py +++ b/twilio/rest/wireless/__init__.py @@ -1,67 +1,43 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" +from warnings import warn -from twilio.base.domain import Domain -from twilio.rest.wireless.v1 import V1 +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(Domain): - - def __init__(self, twilio): - """ - Initialize the Wireless Domain - - :returns: Domain for Wireless - :rtype: twilio.rest.wireless.Wireless - """ - super(Wireless, self).__init__(twilio) - - self.base_url = 'https://wireless.twilio.com' - - # Versions - self._v1 = None - +class Wireless(WirelessBase): @property - def v1(self): - """ - :returns: Version v1 of wireless - :rtype: twilio.rest.wireless.v1.V1 - """ - if self._v1 is None: - self._v1 = V1(self) - return self._v1 + 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): - """ - :rtype: twilio.rest.wireless.v1.command.CommandList - """ + def commands(self) -> CommandList: + warn( + "commands is deprecated. Use v1.commands instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v1.commands @property - def rate_plans(self): - """ - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanList - """ + 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): - """ - :rtype: twilio.rest.wireless.v1.sim.SimList - """ + def sims(self) -> SimList: + warn( + "sims is deprecated. Use v1.sims instead.", DeprecationWarning, stacklevel=2 + ) return self.v1.sims - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/wireless/v1/__init__.py b/twilio/rest/wireless/v1/__init__.py index 7ed77cdef4..8f4d0dc5d7 100644 --- a/twilio/rest/wireless/v1/__init__.py +++ b/twilio/rest/wireless/v1/__init__.py @@ -1,64 +1,67 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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): + def __init__(self, domain: Domain): """ Initialize the V1 version of Wireless - :returns: V1 version of Wireless - :rtype: twilio.rest.wireless.v1.V1.V1 + :param domain: The Twilio.wireless domain """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._commands = None - self._rate_plans = None - self._sims = None + 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): - """ - :rtype: twilio.rest.wireless.v1.command.CommandList - """ + def commands(self) -> CommandList: if self._commands is None: self._commands = CommandList(self) return self._commands @property - def rate_plans(self): - """ - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanList - """ + def rate_plans(self) -> RatePlanList: if self._rate_plans is None: self._rate_plans = RatePlanList(self) return self._rate_plans @property - def sims(self): - """ - :rtype: twilio.rest.wireless.v1.sim.SimList - """ + def sims(self) -> SimList: if self._sims is None: self._sims = SimList(self) return self._sims - def __repr__(self): + @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 - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/wireless/v1/command.py b/twilio/rest/wireless/v1/command.py index db1456c7de..a6e8f0b39d 100644 --- a/twilio/rest/wireless/v1/command.py +++ b/twilio/rest/wireless/v1/command.py @@ -1,451 +1,669 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 CommandList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class CommandInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the CommandList + class CommandMode(object): + TEXT = "text" + BINARY = "binary" - :param Version version: Version that contains the resource + class Direction(object): + FROM_SIM = "from_sim" + TO_SIM = "to_sim" - :returns: twilio.rest.wireless.v1.command.CommandList - :rtype: twilio.rest.wireless.v1.command.CommandList - """ - super(CommandList, self).__init__(version) + class Status(object): + QUEUED = "queued" + SENT = "sent" + DELIVERED = "delivered" + RECEIVED = "received" + FAILED = "failed" - # Path Solution - self._solution = {} - self._uri = '/Commands'.format(**self._solution) + 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") - def stream(self, sim=values.unset, status=values.unset, direction=values.unset, - limit=None, page_size=None): + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CommandContext] = None + + @property + def _proxy(self) -> "CommandContext": """ - 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. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param unicode sim: The sim - :param CommandInstance.Status status: The status - :param CommandInstance.Direction direction: The direction - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :returns: CommandContext for this CommandInstance + """ + if self._context is None: + self._context = CommandContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.wireless.v1.command.CommandInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the CommandInstance - page = self.page(sim=sim, status=status, direction=direction, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, sim=values.unset, status=values.unset, direction=values.unset, - limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists CommandInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the CommandInstance - :param unicode sim: The sim - :param CommandInstance.Status status: The status - :param CommandInstance.Direction direction: The direction - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.wireless.v1.command.CommandInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream( - sim=sim, - status=status, - direction=direction, - limit=limit, - page_size=page_size, - )) + return await self._proxy.delete_async() - def page(self, sim=values.unset, status=values.unset, direction=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "CommandInstance": """ - Retrieve a single page of CommandInstance records from the API. - Request is executed immediately + Fetch the CommandInstance - :param unicode sim: The sim - :param CommandInstance.Status status: The status - :param CommandInstance.Direction direction: The direction - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of CommandInstance - :rtype: twilio.rest.wireless.v1.command.CommandPage + :returns: The fetched CommandInstance """ - params = values.of({ - 'Sim': sim, - 'Status': status, - 'Direction': direction, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return CommandPage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "CommandInstance": """ - Retrieve a specific page of CommandInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the CommandInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of CommandInstance - :rtype: twilio.rest.wireless.v1.command.CommandPage + :returns: The fetched CommandInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return await self._proxy.fetch_async() - return CommandPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def create(self, command, sim=values.unset, callback_method=values.unset, - callback_url=values.unset, command_mode=values.unset, - include_sid=values.unset): + :returns: Machine friendly representation """ - Create a new CommandInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - :param unicode command: The command - :param unicode sim: The sim - :param unicode callback_method: The callback_method - :param unicode callback_url: The callback_url - :param CommandInstance.CommandMode command_mode: The command_mode - :param unicode include_sid: The include_sid +class CommandContext(InstanceContext): - :returns: Newly created CommandInstance - :rtype: twilio.rest.wireless.v1.command.CommandInstance + def __init__(self, version: Version, sid: str): """ - data = values.of({ - 'Command': command, - 'Sim': sim, - 'CallbackMethod': callback_method, - 'CallbackUrl': callback_url, - 'CommandMode': command_mode, - 'IncludeSid': include_sid, - }) + Initialize the CommandContext - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) + :param version: Version that contains the resource + :param sid: The SID of the Command resource to fetch. + """ + super().__init__(version) - return CommandInstance(self._version, payload, ) + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Commands/{sid}".format(**self._solution) - def get(self, sid): + def delete(self) -> bool: """ - Constructs a CommandContext + Deletes the CommandInstance - :param sid: The sid - :returns: twilio.rest.wireless.v1.command.CommandContext - :rtype: twilio.rest.wireless.v1.command.CommandContext + :returns: True if delete succeeds, False otherwise """ - return CommandContext(self._version, sid=sid, ) - def __call__(self, sid): - """ - Constructs a CommandContext + headers = values.of({}) - :param sid: The sid + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - :returns: twilio.rest.wireless.v1.command.CommandContext - :rtype: twilio.rest.wireless.v1.command.CommandContext + async def delete_async(self) -> bool: """ - return CommandContext(self._version, sid=sid, ) + Asynchronous coroutine that deletes the CommandInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class CommandPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> CommandInstance: """ - Initialize the CommandPage + Fetch the CommandInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.wireless.v1.command.CommandPage - :rtype: twilio.rest.wireless.v1.command.CommandPage + :returns: The fetched CommandInstance """ - super(CommandPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) + + headers["Accept"] = "application/json" - def get_instance(self, payload): + 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: """ - Build an instance of CommandInstance + Asynchronous coroutine to fetch the CommandInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.wireless.v1.command.CommandInstance - :rtype: twilio.rest.wireless.v1.command.CommandInstance + :returns: The fetched CommandInstance """ - return CommandInstance(self._version, payload, ) - def __repr__(self): + 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 - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class CommandContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class CommandPage(Page): - def __init__(self, version, sid): + def get_instance(self, payload: Dict[str, Any]) -> CommandInstance: """ - Initialize the CommandContext - - :param Version version: Version that contains the resource - :param sid: The sid + Build an instance of CommandInstance - :returns: twilio.rest.wireless.v1.command.CommandContext - :rtype: twilio.rest.wireless.v1.command.CommandContext + :param payload: Payload response from the API """ - super(CommandContext, self).__init__(version) + return CommandInstance(self._version, payload) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Commands/{sid}'.format(**self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def fetch(self): + :returns: Machine friendly representation """ - Fetch a CommandInstance + return "" + - :returns: Fetched CommandInstance - :rtype: twilio.rest.wireless.v1.command.CommandInstance +class CommandList(ListResource): + + def __init__(self, version: Version): """ - params = values.of({}) + Initialize the CommandList - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + :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"}) - return CommandInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __repr__(self): - """ - Provide a friendly representation + headers["Accept"] = "application/json" - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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"}) -class CommandInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - class Direction(object): - FROM_SIM = "from_sim" - TO_SIM = "to_sim" + headers["Accept"] = "application/json" - class Status(object): - QUEUED = "queued" - SENT = "sent" - DELIVERED = "delivered" - RECEIVED = "received" - FAILED = "failed" + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - class CommandMode(object): - TEXT = "text" - BINARY = "binary" + return CommandInstance(self._version, payload) - def __init__(self, version, payload, sid=None): + 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]: """ - Initialize the 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. - :returns: twilio.rest.wireless.v1.command.CommandInstance - :rtype: twilio.rest.wireless.v1.command.CommandInstance - """ - super(CommandInstance, self).__init__(version) + :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) - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'account_sid': payload['account_sid'], - 'sim_sid': payload['sim_sid'], - 'command': payload['command'], - 'command_mode': payload['command_mode'], - 'status': payload['status'], - 'direction': payload['direction'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - } + :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"], + ) - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + return self._version.stream(page, limits["limit"]) - @property - def _proxy(self): + 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]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: CommandContext for this CommandInstance - :rtype: twilio.rest.wireless.v1.command.CommandContext - """ - if self._context is None: - self._context = CommandContext(self._version, sid=self._solution['sid'], ) - return self._context + :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) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['sid'] + 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"], + ) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + return self._version.stream_async(page, limits["limit"]) - @property - def sim_sid(self): + 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]: """ - :returns: The sim_sid - :rtype: unicode - """ - return self._properties['sim_sid'] + Lists CommandInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def command(self): - """ - :returns: The command - :rtype: unicode - """ - return self._properties['command'] + :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, + ) + ) - @property - def command_mode(self): - """ - :returns: The command_mode - :rtype: CommandInstance.CommandMode - """ - return self._properties['command_mode'] + 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. - @property - def status(self): - """ - :returns: The status - :rtype: CommandInstance.Status + :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: """ - return self._properties['status'] + Retrieve a single page of CommandInstance records from the API. + Request is executed immediately - @property - def direction(self): + :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 """ - :returns: The direction - :rtype: CommandInstance.Direction + 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 """ - return self._properties['direction'] + data = values.of( + { + "Sim": sim, + "Status": status, + "Direction": direction, + "Transport": transport, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def date_created(self): + headers = values.of({"Content-Type": "application/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: """ - :returns: The date_created - :rtype: datetime + 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 """ - return self._properties['date_created'] + response = self._version.domain.twilio.request("GET", target_url) + return CommandPage(self._version, response) - @property - def date_updated(self): + async def get_page_async(self, target_url: str) -> CommandPage: """ - :returns: The date_updated - :rtype: datetime + 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 """ - return self._properties['date_updated'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return CommandPage(self._version, response) - @property - def url(self): + def get(self, sid: str) -> CommandContext: """ - :returns: The url - :rtype: unicode + Constructs a CommandContext + + :param sid: The SID of the Command resource to fetch. """ - return self._properties['url'] + return CommandContext(self._version, sid=sid) - def fetch(self): + def __call__(self, sid: str) -> CommandContext: """ - Fetch a CommandInstance + Constructs a CommandContext - :returns: Fetched CommandInstance - :rtype: twilio.rest.wireless.v1.command.CommandInstance + :param sid: The SID of the Command resource to fetch. """ - return self._proxy.fetch() + return CommandContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/wireless/v1/rate_plan.py b/twilio/rest/wireless/v1/rate_plan.py index dafd1dc104..23efabe9b0 100644 --- a/twilio/rest/wireless/v1/rate_plan.py +++ b/twilio/rest/wireless/v1/rate_plan.py @@ -1,530 +1,728 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 RatePlanList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class RatePlanInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the RatePlanList + 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") - :param Version version: Version that contains the resource + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[RatePlanContext] = None - :returns: twilio.rest.wireless.v1.rate_plan.RatePlanList - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanList + @property + def _proxy(self) -> "RatePlanContext": """ - super(RatePlanList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/RatePlans'.format(**self._solution) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - def stream(self, limit=None, page_size=None): + :returns: RatePlanContext for this 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 int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + if self._context is None: + self._context = RatePlanContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.wireless.v1.rate_plan.RatePlanInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the RatePlanInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists RatePlanInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Asynchronous coroutine that deletes the RatePlanInstance - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.wireless.v1.rate_plan.RatePlanInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_async() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "RatePlanInstance": """ - Retrieve a single page of RatePlanInstance records from the API. - Request is executed immediately + Fetch the RatePlanInstance - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of RatePlanInstance - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanPage + :returns: The fetched RatePlanInstance """ - params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - - return RatePlanPage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "RatePlanInstance": """ - Retrieve a specific page of RatePlanInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the RatePlanInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of RatePlanInstance - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanPage + :returns: The fetched RatePlanInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return RatePlanPage(self._version, response, self._solution) - - def create(self, unique_name=values.unset, friendly_name=values.unset, - data_enabled=values.unset, data_limit=values.unset, - data_metering=values.unset, messaging_enabled=values.unset, - voice_enabled=values.unset, national_roaming_enabled=values.unset, - international_roaming=values.unset, - national_roaming_data_limit=values.unset, - international_roaming_data_limit=values.unset): - """ - Create a new RatePlanInstance - - :param unicode unique_name: The unique_name - :param unicode friendly_name: The friendly_name - :param bool data_enabled: The data_enabled - :param unicode data_limit: The data_limit - :param unicode data_metering: The data_metering - :param bool messaging_enabled: The messaging_enabled - :param bool voice_enabled: The voice_enabled - :param bool national_roaming_enabled: The national_roaming_enabled - :param unicode international_roaming: The international_roaming - :param unicode national_roaming_data_limit: The national_roaming_data_limit - :param unicode international_roaming_data_limit: The international_roaming_data_limit - - :returns: Newly created RatePlanInstance - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanInstance - """ - data = values.of({ - 'UniqueName': unique_name, - 'FriendlyName': friendly_name, - 'DataEnabled': data_enabled, - 'DataLimit': data_limit, - 'DataMetering': data_metering, - 'MessagingEnabled': messaging_enabled, - 'VoiceEnabled': voice_enabled, - 'NationalRoamingEnabled': national_roaming_enabled, - 'InternationalRoaming': serialize.map(international_roaming, lambda e: e), - 'NationalRoamingDataLimit': national_roaming_data_limit, - 'InternationalRoamingDataLimit': international_roaming_data_limit, - }) + return await self._proxy.fetch_async() - payload = self._version.create( - 'POST', - self._uri, - data=data, - ) - - return RatePlanInstance(self._version, payload, ) - - def get(self, sid): + def update( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "RatePlanInstance": """ - Constructs a RatePlanContext + Update the RatePlanInstance - :param sid: The sid + :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: twilio.rest.wireless.v1.rate_plan.RatePlanContext - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanContext + :returns: The updated RatePlanInstance """ - return RatePlanContext(self._version, sid=sid, ) + return self._proxy.update( + unique_name=unique_name, + friendly_name=friendly_name, + ) - def __call__(self, sid): + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "RatePlanInstance": """ - Constructs a RatePlanContext + Asynchronous coroutine to update the RatePlanInstance - :param sid: The sid + :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: twilio.rest.wireless.v1.rate_plan.RatePlanContext - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanContext + :returns: The updated RatePlanInstance """ - return RatePlanContext(self._version, sid=sid, ) + return await self._proxy.update_async( + unique_name=unique_name, + friendly_name=friendly_name, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class RatePlanPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class RatePlanContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the RatePlanPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the RatePlanContext - :returns: twilio.rest.wireless.v1.rate_plan.RatePlanPage - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanPage + :param version: Version that contains the resource + :param sid: The SID of the RatePlan resource to update. """ - super(RatePlanPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/RatePlans/{sid}".format(**self._solution) - def get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of RatePlanInstance + Deletes the RatePlanInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.wireless.v1.rate_plan.RatePlanInstance - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanInstance + :returns: True if delete succeeds, False otherwise """ - return RatePlanInstance(self._version, payload, ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the RatePlanInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class RatePlanContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, sid): + def fetch(self) -> RatePlanInstance: """ - Initialize the RatePlanContext + Fetch the RatePlanInstance - :param Version version: Version that contains the resource - :param sid: The sid - :returns: twilio.rest.wireless.v1.rate_plan.RatePlanContext - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanContext + :returns: The fetched RatePlanInstance """ - super(RatePlanContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/RatePlans/{sid}'.format(**self._solution) + headers = values.of({}) - def fetch(self): + 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: """ - Fetch a RatePlanInstance + Asynchronous coroutine to fetch the RatePlanInstance + - :returns: Fetched RatePlanInstance - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanInstance + :returns: The fetched RatePlanInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], ) + return RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def update(self, unique_name=values.unset, friendly_name=values.unset): + def update( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> RatePlanInstance: """ Update the RatePlanInstance - :param unicode unique_name: The unique_name - :param unicode friendly_name: The friendly_name + :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: Updated RatePlanInstance - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanInstance + :returns: The updated RatePlanInstance """ - data = values.of({'UniqueName': unique_name, 'FriendlyName': friendly_name, }) + + 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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) - return RatePlanInstance(self._version, payload, sid=self._solution['sid'], ) + return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) - def delete(self): + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> RatePlanInstance: """ - Deletes the RatePlanInstance + Asynchronous coroutine to update the RatePlanInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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._version.delete('delete', self._uri) - def __repr__(self): + 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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class RatePlanInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, payload, sid=None): - """ - Initialize the RatePlanInstance - - :returns: twilio.rest.wireless.v1.rate_plan.RatePlanInstance - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanInstance - """ - super(RatePlanInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'unique_name': payload['unique_name'], - 'account_sid': payload['account_sid'], - 'friendly_name': payload['friendly_name'], - 'data_enabled': payload['data_enabled'], - 'data_metering': payload['data_metering'], - 'data_limit': deserialize.integer(payload['data_limit']), - 'messaging_enabled': payload['messaging_enabled'], - 'voice_enabled': payload['voice_enabled'], - 'national_roaming_enabled': payload['national_roaming_enabled'], - 'national_roaming_data_limit': deserialize.integer(payload['national_roaming_data_limit']), - 'international_roaming': payload['international_roaming'], - 'international_roaming_data_limit': deserialize.integer(payload['international_roaming_data_limit']), - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - } - - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } +class RatePlanPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> RatePlanInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of RatePlanInstance - :returns: RatePlanContext for this RatePlanInstance - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = RatePlanContext(self._version, sid=self._solution['sid'], ) - return self._context + return RatePlanInstance(self._version, payload) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['sid'] + Provide a friendly representation - @property - def unique_name(self): - """ - :returns: The unique_name - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['unique_name'] + return "" - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def friendly_name(self): - """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] +class RatePlanList(ListResource): - @property - def data_enabled(self): + def __init__(self, version: Version): """ - :returns: The data_enabled - :rtype: bool - """ - return self._properties['data_enabled'] + Initialize the RatePlanList - @property - def data_metering(self): - """ - :returns: The data_metering - :rtype: unicode - """ - return self._properties['data_metering'] + :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"}) - @property - def data_limit(self): - """ - :returns: The data_limit - :rtype: unicode - """ - return self._properties['data_limit'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def messaging_enabled(self): - """ - :returns: The messaging_enabled - :rtype: bool - """ - return self._properties['messaging_enabled'] + headers["Accept"] = "application/json" - @property - def voice_enabled(self): - """ - :returns: The voice_enabled - :rtype: bool - """ - return self._properties['voice_enabled'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def national_roaming_enabled(self): - """ - :returns: The national_roaming_enabled - :rtype: bool - """ - return self._properties['national_roaming_enabled'] + 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"}) - @property - def national_roaming_data_limit(self): + 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]: """ - :returns: The national_roaming_data_limit - :rtype: unicode + 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 """ - return self._properties['national_roaming_data_limit'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def international_roaming(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RatePlanInstance]: """ - :returns: The international_roaming - :rtype: unicode + 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 """ - return self._properties['international_roaming'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def international_roaming_data_limit(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RatePlanInstance]: """ - :returns: The international_roaming_data_limit - :rtype: unicode + 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 self._properties['international_roaming_data_limit'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def date_created(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RatePlanInstance]: """ - :returns: The date_created - :rtype: datetime + 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: """ - return self._properties['date_created'] + Retrieve a single page of RatePlanInstance records from the API. + Request is executed immediately - @property - def date_updated(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The date_updated - :rtype: datetime + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page of RatePlanInstance records from the API. + Request is executed immediately - @property - def url(self): + :param page_token: PageToken provided by the API + :param page_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 """ - :returns: The url - :rtype: unicode + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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: """ - return self._properties['url'] + Retrieve a specific page of RatePlanInstance records from the API. + Request is executed immediately - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of RatePlanInstance """ - Fetch a RatePlanInstance + response = self._version.domain.twilio.request("GET", target_url) + return RatePlanPage(self._version, response) - :returns: Fetched RatePlanInstance - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanInstance + async def get_page_async(self, target_url: str) -> RatePlanPage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of RatePlanInstance records from the API. + Request is executed immediately - def update(self, unique_name=values.unset, friendly_name=values.unset): + :param target_url: API-generated URL for the requested results page + + :returns: Page of RatePlanInstance """ - Update the RatePlanInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return RatePlanPage(self._version, response) - :param unicode unique_name: The unique_name - :param unicode friendly_name: The friendly_name + def get(self, sid: str) -> RatePlanContext: + """ + Constructs a RatePlanContext - :returns: Updated RatePlanInstance - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanInstance + :param sid: The SID of the RatePlan resource to update. """ - return self._proxy.update(unique_name=unique_name, friendly_name=friendly_name, ) + return RatePlanContext(self._version, sid=sid) - def delete(self): + def __call__(self, sid: str) -> RatePlanContext: """ - Deletes the RatePlanInstance + Constructs a RatePlanContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The SID of the RatePlan resource to update. """ - return self._proxy.delete() + return RatePlanContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/wireless/v1/sim/__init__.py b/twilio/rest/wireless/v1/sim/__init__.py index cf913dbbc0..cba0eeec71 100644 --- a/twilio/rest/wireless/v1/sim/__init__.py +++ b/twilio/rest/wireless/v1/sim/__init__.py @@ -1,710 +1,942 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import values +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 SimList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class SimInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the SimList + class ResetStatus(object): + RESETTING = "resetting" - :param Version version: Version that contains the resource + class Status(object): + NEW = "new" + READY = "ready" + ACTIVE = "active" + SUSPENDED = "suspended" + DEACTIVATED = "deactivated" + CANCELED = "canceled" + SCHEDULED = "scheduled" + UPDATING = "updating" - :returns: twilio.rest.wireless.v1.sim.SimList - :rtype: twilio.rest.wireless.v1.sim.SimList - """ - super(SimList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {} - self._uri = '/Sims'.format(**self._solution) + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[SimContext] = None - def stream(self, status=values.unset, iccid=values.unset, - rate_plan=values.unset, e_id=values.unset, - sim_registration_code=values.unset, limit=None, page_size=None): + @property + def _proxy(self) -> "SimContext": """ - 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 - :param unicode iccid: The iccid - :param unicode rate_plan: The rate_plan - :param unicode e_id: The e_id - :param unicode sim_registration_code: The sim_registration_code - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.wireless.v1.sim.SimInstance] + :returns: SimContext for this SimInstance """ - 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'], limits['page_limit']) + if self._context is None: + self._context = SimContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def list(self, status=values.unset, iccid=values.unset, rate_plan=values.unset, - e_id=values.unset, sim_registration_code=values.unset, limit=None, - page_size=None): + def delete(self) -> bool: """ - Lists SimInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the SimInstance - :param SimInstance.Status status: The status - :param unicode iccid: The iccid - :param unicode rate_plan: The rate_plan - :param unicode e_id: The e_id - :param unicode sim_registration_code: The sim_registration_code - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.wireless.v1.sim.SimInstance] + :returns: True if delete succeeds, False otherwise """ - 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, - )) + return self._proxy.delete() - def page(self, status=values.unset, iccid=values.unset, rate_plan=values.unset, - e_id=values.unset, sim_registration_code=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def delete_async(self) -> bool: """ - Retrieve a single page of SimInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the SimInstance - :param SimInstance.Status status: The status - :param unicode iccid: The iccid - :param unicode rate_plan: The rate_plan - :param unicode e_id: The e_id - :param unicode sim_registration_code: The sim_registration_code - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 - :returns: Page of SimInstance - :rtype: twilio.rest.wireless.v1.sim.SimPage - """ - params = 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, - }) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - response = self._version.page( - 'GET', - self._uri, - params=params, - ) + def fetch(self) -> "SimInstance": + """ + Fetch the SimInstance - return SimPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched SimInstance """ - Retrieve a specific page of SimInstance records from the API. - Request is executed immediately + return self._proxy.fetch() - :param str target_url: API-generated URL for the requested results page + 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 - :returns: Page of SimInstance - :rtype: twilio.rest.wireless.v1.sim.SimPage + :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 """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, ) - return SimPage(self._version, response, self._solution) + 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, + ) - def get(self, sid): + @property + def data_sessions(self) -> DataSessionList: """ - Constructs a SimContext - - :param sid: The sid - - :returns: twilio.rest.wireless.v1.sim.SimContext - :rtype: twilio.rest.wireless.v1.sim.SimContext + Access the data_sessions """ - return SimContext(self._version, sid=sid, ) + return self._proxy.data_sessions - def __call__(self, sid): + @property + def usage_records(self) -> UsageRecordList: """ - Constructs a SimContext - - :param sid: The sid - - :returns: twilio.rest.wireless.v1.sim.SimContext - :rtype: twilio.rest.wireless.v1.sim.SimContext + Access the usage_records """ - return SimContext(self._version, sid=sid, ) + return self._proxy.usage_records - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class SimPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class SimContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the SimPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the SimContext - :returns: twilio.rest.wireless.v1.sim.SimPage - :rtype: twilio.rest.wireless.v1.sim.SimPage + :param version: Version that contains the resource + :param sid: The SID or the `unique_name` of the Sim resource to update. """ - super(SimPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/Sims/{sid}".format(**self._solution) - def get_instance(self, payload): + self._data_sessions: Optional[DataSessionList] = None + self._usage_records: Optional[UsageRecordList] = None + + def delete(self) -> bool: """ - Build an instance of SimInstance + Deletes the SimInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.wireless.v1.sim.SimInstance - :rtype: twilio.rest.wireless.v1.sim.SimInstance + :returns: True if delete succeeds, False otherwise """ - return SimInstance(self._version, payload, ) - def __repr__(self): + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Provide a friendly representation + Asynchronous coroutine that deletes the SimInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class SimContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, sid): + def fetch(self) -> SimInstance: """ - Initialize the SimContext + Fetch the SimInstance - :param Version version: Version that contains the resource - :param sid: The sid - :returns: twilio.rest.wireless.v1.sim.SimContext - :rtype: twilio.rest.wireless.v1.sim.SimContext + :returns: The fetched SimInstance """ - super(SimContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Sims/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - # Dependents - self._usage_records = None - self._data_sessions = None + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SimInstance: """ - Fetch a SimInstance + Asynchronous coroutine to fetch the SimInstance + - :returns: Fetched SimInstance - :rtype: twilio.rest.wireless.v1.sim.SimInstance + :returns: The fetched SimInstance """ - params = values.of({}) - payload = self._version.fetch( - 'GET', - self._uri, - params=params, + 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'], ) + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def update(self, unique_name=values.unset, callback_method=values.unset, - callback_url=values.unset, friendly_name=values.unset, - rate_plan=values.unset, status=values.unset, - commands_callback_method=values.unset, - commands_callback_url=values.unset, sms_fallback_method=values.unset, - sms_fallback_url=values.unset, sms_method=values.unset, - sms_url=values.unset, voice_fallback_method=values.unset, - voice_fallback_url=values.unset, voice_method=values.unset, - voice_url=values.unset): + 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 unicode unique_name: The unique_name - :param unicode callback_method: The callback_method - :param unicode callback_url: The callback_url - :param unicode friendly_name: The friendly_name - :param unicode rate_plan: The rate_plan - :param SimInstance.Status status: The status - :param unicode commands_callback_method: The commands_callback_method - :param unicode commands_callback_url: The commands_callback_url - :param unicode sms_fallback_method: The sms_fallback_method - :param unicode sms_fallback_url: The sms_fallback_url - :param unicode sms_method: The sms_method - :param unicode sms_url: The sms_url - :param unicode voice_fallback_method: The voice_fallback_method - :param unicode voice_fallback_url: The voice_fallback_url - :param unicode voice_method: The voice_method - :param unicode voice_url: The voice_url - - :returns: Updated SimInstance - :rtype: twilio.rest.wireless.v1.sim.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, - }) + :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( - 'POST', - self._uri, - data=data, + method="POST", uri=self._uri, data=data, headers=headers ) - return SimInstance(self._version, payload, sid=self._solution['sid'], ) + 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({}) - @property - def usage_records(self): - """ - Access the usage_records + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: twilio.rest.wireless.v1.sim.usage_record.UsageRecordList - :rtype: twilio.rest.wireless.v1.sim.usage_record.UsageRecordList - """ - if self._usage_records is None: - self._usage_records = UsageRecordList(self._version, sim_sid=self._solution['sid'], ) - return self._usage_records + 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): + def data_sessions(self) -> DataSessionList: """ Access the data_sessions - - :returns: twilio.rest.wireless.v1.sim.data_session.DataSessionList - :rtype: twilio.rest.wireless.v1.sim.data_session.DataSessionList """ if self._data_sessions is None: - self._data_sessions = DataSessionList(self._version, sim_sid=self._solution['sid'], ) + self._data_sessions = DataSessionList( + self._version, + self._solution["sid"], + ) return self._data_sessions - def __repr__(self): + @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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class SimInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - class Status(object): - NEW = "new" - READY = "ready" - ACTIVE = "active" - SUSPENDED = "suspended" - DEACTIVATED = "deactivated" - CANCELED = "canceled" - SCHEDULED = "scheduled" - UPDATING = "updating" + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - def __init__(self, version, payload, sid=None): - """ - Initialize the SimInstance - - :returns: twilio.rest.wireless.v1.sim.SimInstance - :rtype: twilio.rest.wireless.v1.sim.SimInstance - """ - super(SimInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'unique_name': payload['unique_name'], - 'account_sid': payload['account_sid'], - 'rate_plan_sid': payload['rate_plan_sid'], - 'friendly_name': payload['friendly_name'], - 'iccid': payload['iccid'], - 'e_id': payload['e_id'], - 'status': payload['status'], - 'commands_callback_url': payload['commands_callback_url'], - 'commands_callback_method': payload['commands_callback_method'], - 'sms_fallback_method': payload['sms_fallback_method'], - 'sms_fallback_url': payload['sms_fallback_url'], - 'sms_method': payload['sms_method'], - 'sms_url': payload['sms_url'], - 'voice_fallback_method': payload['voice_fallback_method'], - 'voice_fallback_url': payload['voice_fallback_url'], - 'voice_method': payload['voice_method'], - 'voice_url': payload['voice_url'], - 'date_created': deserialize.iso8601_datetime(payload['date_created']), - 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), - 'url': payload['url'], - 'links': payload['links'], - 'ip_address': payload['ip_address'], - } - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } +class SimPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> SimInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Build an instance of SimInstance - :returns: SimContext for this SimInstance - :rtype: twilio.rest.wireless.v1.sim.SimContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = SimContext(self._version, sid=self._solution['sid'], ) - return self._context + return SimInstance(self._version, payload) - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['sid'] + Provide a friendly representation - @property - def unique_name(self): - """ - :returns: The unique_name - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['unique_name'] + return "" - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def rate_plan_sid(self): - """ - :returns: The rate_plan_sid - :rtype: unicode - """ - return self._properties['rate_plan_sid'] +class SimList(ListResource): - @property - def friendly_name(self): + def __init__(self, version: Version): """ - :returns: The friendly_name - :rtype: unicode - """ - return self._properties['friendly_name'] + Initialize the SimList - @property - def iccid(self): - """ - :returns: The iccid - :rtype: unicode - """ - return self._properties['iccid'] + :param version: Version that contains the resource - @property - def e_id(self): - """ - :returns: The e_id - :rtype: unicode """ - return self._properties['e_id'] + super().__init__(version) - @property - def status(self): - """ - :returns: The status - :rtype: SimInstance.Status - """ - return self._properties['status'] + self._uri = "/Sims" - @property - def commands_callback_url(self): - """ - :returns: The commands_callback_url - :rtype: unicode + 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]: """ - return self._properties['commands_callback_url'] + 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. - @property - def commands_callback_method(self): - """ - :returns: The commands_callback_method - :rtype: unicode - """ - return self._properties['commands_callback_method'] + :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) - @property - def sms_fallback_method(self): - """ - :returns: The sms_fallback_method - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['sms_fallback_method'] + 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"], + ) - @property - def sms_fallback_url(self): - """ - :returns: The sms_fallback_url - :rtype: unicode - """ - return self._properties['sms_fallback_url'] + return self._version.stream(page, limits["limit"]) - @property - def sms_method(self): - """ - :returns: The sms_method - :rtype: unicode + 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]: """ - return self._properties['sms_method'] + 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. - @property - def sms_url(self): - """ - :returns: The sms_url - :rtype: unicode - """ - return self._properties['sms_url'] + :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) - @property - def voice_fallback_method(self): - """ - :returns: The voice_fallback_method - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['voice_fallback_method'] + 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"], + ) - @property - def voice_fallback_url(self): - """ - :returns: The voice_fallback_url - :rtype: unicode - """ - return self._properties['voice_fallback_url'] + return self._version.stream_async(page, limits["limit"]) - @property - def voice_method(self): + 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]: """ - :returns: The voice_method - :rtype: unicode - """ - return self._properties['voice_method'] + Lists SimInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def voice_url(self): - """ - :returns: The voice_url - :rtype: unicode - """ - return self._properties['voice_url'] + :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, + ) + ) - @property - def date_created(self): - """ - :returns: The date_created - :rtype: datetime - """ - return self._properties['date_created'] + 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. - @property - def date_updated(self): - """ - :returns: The date_updated - :rtype: datetime + :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: """ - return self._properties['date_updated'] + Retrieve a single page of SimInstance records from the API. + Request is executed immediately - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] + :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 - @property - def links(self): - """ - :returns: The links - :rtype: unicode + :returns: Page of SimInstance """ - return self._properties['links'] + 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, + } + ) - @property - def ip_address(self): - """ - :returns: The ip_address - :rtype: unicode + headers = values.of({"Content-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 """ - return self._properties['ip_address'] + 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, + } + ) - def fetch(self): + headers = values.of({"Content-Type": "application/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: """ - Fetch a SimInstance + 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: Fetched SimInstance - :rtype: twilio.rest.wireless.v1.sim.SimInstance + :returns: Page of SimInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return SimPage(self._version, response) - def update(self, unique_name=values.unset, callback_method=values.unset, - callback_url=values.unset, friendly_name=values.unset, - rate_plan=values.unset, status=values.unset, - commands_callback_method=values.unset, - commands_callback_url=values.unset, sms_fallback_method=values.unset, - sms_fallback_url=values.unset, sms_method=values.unset, - sms_url=values.unset, voice_fallback_method=values.unset, - voice_fallback_url=values.unset, voice_method=values.unset, - voice_url=values.unset): + async def get_page_async(self, target_url: str) -> SimPage: """ - Update the SimInstance + 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 - :param unicode unique_name: The unique_name - :param unicode callback_method: The callback_method - :param unicode callback_url: The callback_url - :param unicode friendly_name: The friendly_name - :param unicode rate_plan: The rate_plan - :param SimInstance.Status status: The status - :param unicode commands_callback_method: The commands_callback_method - :param unicode commands_callback_url: The commands_callback_url - :param unicode sms_fallback_method: The sms_fallback_method - :param unicode sms_fallback_url: The sms_fallback_url - :param unicode sms_method: The sms_method - :param unicode sms_url: The sms_url - :param unicode voice_fallback_method: The voice_fallback_method - :param unicode voice_fallback_url: The voice_fallback_url - :param unicode voice_method: The voice_method - :param unicode voice_url: The voice_url - - :returns: Updated SimInstance - :rtype: twilio.rest.wireless.v1.sim.SimInstance + :returns: Page of 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, - ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return SimPage(self._version, response) - @property - def usage_records(self): + def get(self, sid: str) -> SimContext: """ - Access the usage_records + Constructs a SimContext - :returns: twilio.rest.wireless.v1.sim.usage_record.UsageRecordList - :rtype: twilio.rest.wireless.v1.sim.usage_record.UsageRecordList + :param sid: The SID or the `unique_name` of the Sim resource to update. """ - return self._proxy.usage_records + return SimContext(self._version, sid=sid) - @property - def data_sessions(self): + def __call__(self, sid: str) -> SimContext: """ - Access the data_sessions + Constructs a SimContext - :returns: twilio.rest.wireless.v1.sim.data_session.DataSessionList - :rtype: twilio.rest.wireless.v1.sim.data_session.DataSessionList + :param sid: The SID or the `unique_name` of the Sim resource to update. """ - return self._proxy.data_sessions + return SimContext(self._version, sid=sid) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" diff --git a/twilio/rest/wireless/v1/sim/data_session.py b/twilio/rest/wireless/v1/sim/data_session.py index 26b1d1499f..b4c50d608d 100644 --- a/twilio/rest/wireless/v1/sim/data_session.py +++ b/twilio/rest/wireless/v1/sim/data_session.py @@ -1,346 +1,327 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import deserialize -from twilio.base import serialize -from twilio.base import values +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 DataSessionList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, sim_sid): - """ - Initialize the DataSessionList - - :param Version version: Version that contains the resource - :param sim_sid: The sim_sid - - :returns: twilio.rest.wireless.v1.sim.data_session.DataSessionList - :rtype: twilio.rest.wireless.v1.sim.data_session.DataSessionList - """ - super(DataSessionList, self).__init__(version) +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") - # Path Solution - self._solution = {'sim_sid': sim_sid, } - self._uri = '/Sims/{sim_sid}/DataSessions'.format(**self._solution) + self._solution = { + "sim_sid": sim_sid, + } - def stream(self, end=values.unset, start=values.unset, limit=None, - page_size=None): + def __repr__(self) -> str: """ - 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 datetime end: The end - :param datetime start: The start - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + Provide a friendly representation - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.wireless.v1.sim.data_session.DataSessionInstance] + :returns: Machine friendly representation """ - limits = self._version.read_limits(limit, page_size) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - page = self.page(end=end, start=start, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit'], limits['page_limit']) +class DataSessionPage(Page): - def list(self, end=values.unset, start=values.unset, limit=None, - page_size=None): + def get_instance(self, payload: Dict[str, Any]) -> 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 datetime end: The end - :param datetime start: The start - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + Build an instance of DataSessionInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.wireless.v1.sim.data_session.DataSessionInstance] + :param payload: Payload response from the API """ - return list(self.stream(end=end, start=start, limit=limit, page_size=page_size, )) + return DataSessionInstance( + self._version, payload, sim_sid=self._solution["sim_sid"] + ) - def page(self, end=values.unset, start=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def __repr__(self) -> str: """ - Retrieve a single page of DataSessionInstance records from the API. - Request is executed immediately - - :param datetime end: The end - :param datetime start: The start - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + Provide a friendly representation - :returns: Page of DataSessionInstance - :rtype: twilio.rest.wireless.v1.sim.data_session.DataSessionPage + :returns: Machine friendly representation """ - params = values.of({ - 'End': serialize.iso8601_datetime(end), - 'Start': serialize.iso8601_datetime(start), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return "" - response = self._version.page( - 'GET', - self._uri, - params=params, - ) - return DataSessionPage(self._version, response, self._solution) +class DataSessionList(ListResource): - def get_page(self, target_url): + def __init__(self, version: Version, sim_sid: str): """ - Retrieve a specific page of DataSessionInstance records from the API. - Request is executed immediately + Initialize the DataSessionList - :param str target_url: API-generated URL for the requested results page + :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. - :returns: Page of DataSessionInstance - :rtype: twilio.rest.wireless.v1.sim.data_session.DataSessionPage """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return DataSessionPage(self._version, response, self._solution) + super().__init__(version) - def __repr__(self): - """ - Provide a friendly representation + # Path Solution + self._solution = { + "sim_sid": sim_sid, + } + self._uri = "/Sims/{sim_sid}/DataSessions".format(**self._solution) - :returns: Machine friendly representation - :rtype: str + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DataSessionInstance]: """ - return '' - + 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. -class DataSessionPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - def __init__(self, version, response, solution): + :returns: Generator that will yield up to limit results """ - Initialize the DataSessionPage + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param sim_sid: The sim_sid + return self._version.stream(page, limits["limit"]) - :returns: twilio.rest.wireless.v1.sim.data_session.DataSessionPage - :rtype: twilio.rest.wireless.v1.sim.data_session.DataSessionPage + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DataSessionInstance]: """ - super(DataSessionPage, self).__init__(version, response) + 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. - # Path Solution - self._solution = solution + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - def get_instance(self, payload): + :returns: Generator that will yield up to limit results """ - Build an instance of DataSessionInstance + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - :param dict payload: Payload response from the API + return self._version.stream_async(page, limits["limit"]) - :returns: twilio.rest.wireless.v1.sim.data_session.DataSessionInstance - :rtype: twilio.rest.wireless.v1.sim.data_session.DataSessionInstance + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DataSessionInstance]: """ - return DataSessionInstance(self._version, payload, sim_sid=self._solution['sim_sid'], ) + Lists DataSessionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - def __repr__(self): - """ - Provide a friendly representation + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - :returns: Machine friendly representation - :rtype: str + :returns: list that will contain up to limit results """ - return '' - - -class DataSessionInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - def __init__(self, version, payload, sim_sid): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DataSessionInstance]: """ - Initialize the 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. - :returns: twilio.rest.wireless.v1.sim.data_session.DataSessionInstance - :rtype: twilio.rest.wireless.v1.sim.data_session.DataSessionInstance + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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: """ - super(DataSessionInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload['sid'], - 'sim_sid': payload['sim_sid'], - 'account_sid': payload['account_sid'], - 'radio_link': payload['radio_link'], - 'operator_mcc': payload['operator_mcc'], - 'operator_mnc': payload['operator_mnc'], - 'operator_country': payload['operator_country'], - 'operator_name': payload['operator_name'], - 'cell_id': payload['cell_id'], - 'cell_location_estimate': payload['cell_location_estimate'], - 'packets_uploaded': deserialize.integer(payload['packets_uploaded']), - 'packets_downloaded': deserialize.integer(payload['packets_downloaded']), - 'last_updated': deserialize.iso8601_datetime(payload['last_updated']), - 'start': deserialize.iso8601_datetime(payload['start']), - 'end': deserialize.iso8601_datetime(payload['end']), - } + Retrieve a single page of DataSessionInstance records from the API. + Request is executed immediately - # Context - self._context = None - self._solution = {'sim_sid': sim_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 - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode + :returns: Page of DataSessionInstance """ - return self._properties['sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def sim_sid(self): - """ - :returns: The sim_sid - :rtype: unicode - """ - return self._properties['sim_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + headers["Accept"] = "application/json" - @property - def radio_link(self): - """ - :returns: The radio_link - :rtype: unicode - """ - return self._properties['radio_link'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DataSessionPage(self._version, response, self._solution) - @property - def operator_mcc(self): + 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: """ - :returns: The operator_mcc - :rtype: unicode - """ - return self._properties['operator_mcc'] + Asynchronously retrieve a single page of DataSessionInstance records from the API. + Request is executed immediately - @property - def operator_mnc(self): - """ - :returns: The operator_mnc - :rtype: unicode - """ - return self._properties['operator_mnc'] + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - @property - def operator_country(self): - """ - :returns: The operator_country - :rtype: unicode + :returns: Page of DataSessionInstance """ - return self._properties['operator_country'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def operator_name(self): - """ - :returns: The operator_name - :rtype: unicode - """ - return self._properties['operator_name'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def cell_id(self): - """ - :returns: The cell_id - :rtype: unicode - """ - return self._properties['cell_id'] + headers["Accept"] = "application/json" - @property - def cell_location_estimate(self): - """ - :returns: The cell_location_estimate - :rtype: dict - """ - return self._properties['cell_location_estimate'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DataSessionPage(self._version, response, self._solution) - @property - def packets_uploaded(self): - """ - :returns: The packets_uploaded - :rtype: unicode + def get_page(self, target_url: str) -> DataSessionPage: """ - return self._properties['packets_uploaded'] + Retrieve a specific page of DataSessionInstance records from the API. + Request is executed immediately - @property - def packets_downloaded(self): - """ - :returns: The packets_downloaded - :rtype: unicode - """ - return self._properties['packets_downloaded'] + :param target_url: API-generated URL for the requested results page - @property - def last_updated(self): - """ - :returns: The last_updated - :rtype: datetime + :returns: Page of DataSessionInstance """ - return self._properties['last_updated'] + response = self._version.domain.twilio.request("GET", target_url) + return DataSessionPage(self._version, response, self._solution) - @property - def start(self): - """ - :returns: The start - :rtype: datetime + async def get_page_async(self, target_url: str) -> DataSessionPage: """ - return self._properties['start'] + Asynchronously retrieve a specific page of DataSessionInstance records from the API. + Request is executed immediately - @property - def end(self): - """ - :returns: The end - :rtype: datetime + :param target_url: API-generated URL for the requested results page + + :returns: Page of DataSessionInstance """ - return self._properties['end'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return DataSessionPage(self._version, response, self._solution) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/wireless/v1/sim/usage_record.py b/twilio/rest/wireless/v1/sim/usage_record.py index 70b3418073..1cd26b6c2e 100644 --- a/twilio/rest/wireless/v1/sim/usage_record.py +++ b/twilio/rest/wireless/v1/sim/usage_record.py @@ -1,271 +1,353 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / +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 twilio.base import serialize -from twilio.base import values +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 "".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 "" + + class UsageRecordList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - def __init__(self, version, sim_sid): + def __init__(self, version: Version, sim_sid: str): """ Initialize the UsageRecordList - :param Version version: Version that contains the resource - :param sim_sid: The sim_sid + :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. - :returns: twilio.rest.wireless.v1.sim.usage_record.UsageRecordList - :rtype: twilio.rest.wireless.v1.sim.usage_record.UsageRecordList """ - super(UsageRecordList, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'sim_sid': sim_sid, } - self._uri = '/Sims/{sim_sid}/UsageRecords'.format(**self._solution) + self._solution = { + "sim_sid": sim_sid, + } + self._uri = "/Sims/{sim_sid}/UsageRecords".format(**self._solution) - def stream(self, end=values.unset, start=values.unset, granularity=values.unset, - limit=None, page_size=None): + 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: The end - :param datetime start: The start - :param UsageRecordInstance.Granularity granularity: The granularity - :param int limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) + :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 - :rtype: list[twilio.rest.wireless.v1.sim.usage_record.UsageRecordInstance] """ limits = self._version.read_limits(limit, page_size) + page = self.page( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) - page = self.page(end=end, start=start, granularity=granularity, page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit'], limits['page_limit']) + return self._version.stream(page, limits["limit"]) - def list(self, end=values.unset, start=values.unset, granularity=values.unset, - limit=None, page_size=None): + 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]: """ - Lists UsageRecordInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + 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: The end - :param datetime start: The start - :param UsageRecordInstance.Granularity granularity: The granularity - :param int limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param int page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) + :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 - :rtype: list[twilio.rest.wireless.v1.sim.usage_record.UsageRecordInstance] """ - return list(self.stream( - end=end, - start=start, - granularity=granularity, - limit=limit, - page_size=page_size, - )) - - def page(self, end=values.unset, start=values.unset, granularity=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of UsageRecordInstance records from the API. - Request is executed immediately + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) - :param datetime end: The end - :param datetime start: The start - :param UsageRecordInstance.Granularity granularity: The granularity - :param str page_token: PageToken provided by the API - :param int page_number: Page Number, this value is simply for client state - :param int page_size: Number of records to return, defaults to 50 + return self._version.stream_async(page, limits["limit"]) - :returns: Page of UsageRecordInstance - :rtype: twilio.rest.wireless.v1.sim.usage_record.UsageRecordPage + 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]: """ - params = values.of({ - 'End': serialize.iso8601_datetime(end), - 'Start': serialize.iso8601_datetime(start), - 'Granularity': granularity, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Lists UsageRecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - response = self._version.page( - 'GET', - self._uri, - params=params, + :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, + ) ) - return UsageRecordPage(self._version, response, self._solution) + 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. - def get_page(self, target_url): + :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 specific page of UsageRecordInstance records from the API. + Retrieve a single page of UsageRecordInstance records from the API. Request is executed immediately - :param str target_url: API-generated URL for the requested results page + :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 - :rtype: twilio.rest.wireless.v1.sim.usage_record.UsageRecordPage """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + data = values.of( + { + "End": serialize.iso8601_datetime(end), + "Start": serialize.iso8601_datetime(start), + "Granularity": granularity, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } ) - return UsageRecordPage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class UsageRecordPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, response, solution): - """ - Initialize the UsageRecordPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param sim_sid: The sim_sid - - :returns: twilio.rest.wireless.v1.sim.usage_record.UsageRecordPage - :rtype: twilio.rest.wireless.v1.sim.usage_record.UsageRecordPage - """ - super(UsageRecordPage, self).__init__(version, response) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of UsageRecordInstance + headers["Accept"] = "application/json" - :param dict payload: Payload response from the API + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsageRecordPage(self._version, response, self._solution) - :returns: twilio.rest.wireless.v1.sim.usage_record.UsageRecordInstance - :rtype: twilio.rest.wireless.v1.sim.usage_record.UsageRecordInstance - """ - return UsageRecordInstance(self._version, payload, sim_sid=self._solution['sim_sid'], ) + 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 - def __repr__(self): - """ - Provide a friendly representation + :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: Machine friendly representation - :rtype: str + :returns: Page of UsageRecordInstance """ - return '' + 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"}) -class UsageRecordInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - class Granularity(object): - HOURLY = "hourly" - DAILY = "daily" - ALL = "all" + headers["Accept"] = "application/json" - def __init__(self, version, payload, sim_sid): - """ - Initialize the UsageRecordInstance + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsageRecordPage(self._version, response, self._solution) - :returns: twilio.rest.wireless.v1.sim.usage_record.UsageRecordInstance - :rtype: twilio.rest.wireless.v1.sim.usage_record.UsageRecordInstance + def get_page(self, target_url: str) -> UsageRecordPage: """ - super(UsageRecordInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sim_sid': payload['sim_sid'], - 'account_sid': payload['account_sid'], - 'period': payload['period'], - 'commands': payload['commands'], - 'data': payload['data'], - } - - # Context - self._context = None - self._solution = {'sim_sid': sim_sid, } + Retrieve a specific page of UsageRecordInstance records from the API. + Request is executed immediately - @property - def sim_sid(self): - """ - :returns: The sim_sid - :rtype: unicode - """ - return self._properties['sim_sid'] + :param target_url: API-generated URL for the requested results page - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode + :returns: Page of UsageRecordInstance """ - return self._properties['account_sid'] + response = self._version.domain.twilio.request("GET", target_url) + return UsageRecordPage(self._version, response, self._solution) - @property - def period(self): + async def get_page_async(self, target_url: str) -> UsageRecordPage: """ - :returns: The period - :rtype: dict - """ - return self._properties['period'] + Asynchronously retrieve a specific page of UsageRecordInstance records from the API. + Request is executed immediately - @property - def commands(self): - """ - :returns: The commands - :rtype: dict - """ - return self._properties['commands'] + :param target_url: API-generated URL for the requested results page - @property - def data(self): - """ - :returns: The data - :rtype: dict + :returns: Page of UsageRecordInstance """ - return self._properties['data'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return UsageRecordPage(self._version, response, self._solution) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" 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 "" + + +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 "" + + +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 "" diff --git a/twilio/twiml/__init__.py b/twilio/twiml/__init__.py index 97892de90e..70a4df8309 100644 --- a/twilio/twiml/__init__.py +++ b/twilio/twiml/__init__.py @@ -1,21 +1,13 @@ -# coding=utf-8 -""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - import json import re import xml.etree.ElementTree as ET def lower_camel(string): - if not string or '_' not in string: + if not string or "_" not in string: return string - result = "".join([x.title() for x in string.split('_')]) + result = "".join([x.title() for x in string.split("_")]) return result[0].lower() + result[1:] @@ -28,10 +20,10 @@ def format_language(language): 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.') + 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() + return language[0:2].lower() + "-" + language[3:5].upper() class TwiMLException(Exception): @@ -40,7 +32,11 @@ class TwiMLException(Exception): class TwiML(object): MAP = { - 'from_': 'from' + "from_": "from", + "xml_lang": "xml:lang", + "interpret_as": "interpret-as", + "for_": "for", + "break_": "break", } def __init__(self, **kwargs): @@ -68,8 +64,12 @@ def to_xml(self, xml_declaration=True): :param bool xml_declaration: Include the XML declaration. Defaults to True """ - xml = ET.tostring(self.xml()).decode('utf-8') - return '{}'.format(xml) if xml_declaration else xml + xml = ET.tostring(self.xml(), encoding="utf-8").decode("utf-8") + return ( + '{}'.format(xml) + if xml_declaration + else xml + ) def append(self, verb): """ @@ -79,10 +79,7 @@ def append(self, verb): :returns: self """ - if not isinstance(verb, TwiML): - raise TwiMLException('Only appending of TwiML is allowed') - - self.verbs.append(verb) + self.nest(verb) return self def nest(self, verb): @@ -93,8 +90,8 @@ def nest(self, verb): :returns: the TwiML verb """ - if not isinstance(verb, TwiML): - raise TwiMLException('Only nesting of TwiML is allowed') + 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 @@ -118,7 +115,26 @@ def xml(self): el.text = self.value + last_child = None + for verb in self.verbs: - el.append(verb.xml()) + 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 index 81d7ae3cab..89233bd407 100644 --- a/twilio/twiml/fax_response.py +++ b/twilio/twiml/fax_response.py @@ -1,41 +1,59 @@ # coding=utf-8 -""" +r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ -import json from twilio.twiml import ( TwiML, - format_language, ) class FaxResponse(TwiML): - """ TwiML for Faxes """ + """ TwiML for Faxes""" def __init__(self, **kwargs): super(FaxResponse, self).__init__(**kwargs) - self.name = 'Response' - - def receive(self, action=None, method=None, **kwargs): + self.name = "Response" + + def receive( + self, + action=None, + method=None, + media_type=None, + page_size=None, + store_media=None, + **kwargs + ): """ Create a 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: element """ - return self.nest(Receive(action=action, method=method, **kwargs)) + return self.nest( + Receive( + action=action, + method=method, + media_type=media_type, + page_size=page_size, + store_media=store_media, + **kwargs + ) + ) class Receive(TwiML): - """ TwiML Verb """ + """ TwiML Verb""" def __init__(self, **kwargs): super(Receive, self).__init__(**kwargs) - self.name = 'Receive' + self.name = "Receive" diff --git a/twilio/twiml/messaging_response.py b/twilio/twiml/messaging_response.py index 323ea28708..ec36c74c06 100644 --- a/twilio/twiml/messaging_response.py +++ b/twilio/twiml/messaging_response.py @@ -1,49 +1,57 @@ # coding=utf-8 -""" +r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ -import json from twilio.twiml import ( TwiML, - format_language, ) class MessagingResponse(TwiML): - """ TwiML for Messages """ + """ 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): + self.name = "Response" + + def message( + self, + body=None, + to=None, + from_=None, + action=None, + method=None, + status_callback=None, + **kwargs + ): """ Create a element :param body: Message Body :param to: Phone Number to send Message to :param from: Phone Number to send Message from - :param action: Action URL + :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: element """ - return self.nest(Message( - body=body, - to=to, - from_=from_, - action=action, - method=method, - status_callback=status_callback, - **kwargs - )) + 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): """ @@ -59,20 +67,20 @@ def redirect(self, url, method=None, **kwargs): class Redirect(TwiML): - """ TwiML Verb """ + """ TwiML Verb""" def __init__(self, url, **kwargs): super(Redirect, self).__init__(**kwargs) - self.name = 'Redirect' + self.name = "Redirect" self.value = url class Message(TwiML): - """ TwiML Verb """ + """ TwiML Verb""" def __init__(self, body=None, **kwargs): super(Message, self).__init__(**kwargs) - self.name = 'Message' + self.name = "Message" if body: self.value = body @@ -100,18 +108,18 @@ def media(self, url, **kwargs): class Media(TwiML): - """ TwiML Noun """ + """ TwiML Noun""" def __init__(self, url, **kwargs): super(Media, self).__init__(**kwargs) - self.name = 'Media' + self.name = "Media" self.value = url class Body(TwiML): - """ TwiML Noun """ + """ TwiML Noun""" def __init__(self, message, **kwargs): super(Body, self).__init__(**kwargs) - self.name = 'Body' + self.name = "Body" self.value = message diff --git a/twilio/twiml/voice_response.py b/twilio/twiml/voice_response.py index 7077b02e6c..18078b90a3 100644 --- a/twilio/twiml/voice_response.py +++ b/twilio/twiml/voice_response.py @@ -1,31 +1,58 @@ # coding=utf-8 -""" +r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ -import json from twilio.twiml import ( TwiML, - format_language, ) class VoiceResponse(TwiML): - """ TwiML for Voice """ + """ TwiML for Voice""" def __init__(self, **kwargs): super(VoiceResponse, self).__init__(**kwargs) - self.name = 'Response' + self.name = "Response" + + def connect(self, action=None, method=None, **kwargs): + """ + Create a element + + :param action: Action URL + :param method: Action URL method + :param kwargs: additional attributes - 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, **kwargs): + :returns: 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 element @@ -43,27 +70,39 @@ def dial(self, number=None, action=None, method=None, timeout=None, :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: 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, - **kwargs - )) + 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): """ @@ -75,13 +114,23 @@ def echo(self, **kwargs): """ return self.nest(Echo(**kwargs)) - def enqueue(self, name=None, action=None, method=None, wait_url=None, - wait_url_method=None, workflow_sid=None, **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 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 @@ -90,21 +139,41 @@ def enqueue(self, name=None, action=None, method=None, wait_url=None, :returns: element """ - return self.nest(Enqueue( - name=name, - action=action, - 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, **kwargs): + 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 element @@ -122,27 +191,37 @@ def gather(self, input=None, action=None, method=None, timeout=None, :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: 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, - **kwargs - )) + 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): """ @@ -188,8 +267,15 @@ def play(self, url=None, loop=None, digits=None, **kwargs): """ 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): + def queue( + self, + name, + url=None, + method=None, + reservation_sid=None, + post_work_activity_sid=None, + **kwargs + ): """ Create a element @@ -202,20 +288,33 @@ def queue(self, name, url=None, method=None, reservation_sid=None, :returns: 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, transcribe=None, - transcribe_callback=None, **kwargs): + 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 element @@ -228,26 +327,30 @@ def record(self, action=None, method=None, timeout=None, finish_on_key=None, :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: 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, - transcribe=transcribe, - transcribe_callback=transcribe_callback, - **kwargs - )) + 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): """ @@ -272,22 +375,32 @@ def reject(self, reason=None, **kwargs): """ return self.nest(Reject(reason=reason, **kwargs)) - def say(self, message, voice=None, loop=None, language=None, **kwargs): + def say(self, message=None, voice=None, loop=None, language=None, **kwargs): """ Create a element :param message: Message to say :param voice: Voice to use :param loop: Times to loop message - :param language: Message langauge + :param language: Message language :param kwargs: additional attributes :returns: element """ - return self.nest(Say(message, voice=voice, loop=loop, language=language, **kwargs)) - - def sms(self, message, to=None, from_=None, action=None, method=None, - status_callback=None, **kwargs): + 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 element @@ -301,134 +414,562 @@ def sms(self, message, to=None, from_=None, action=None, method=None, :returns: element """ - return self.nest(Sms( - message, - to=to, - from_=from_, - action=action, - method=method, - status_callback=status_callback, - **kwargs - )) + 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 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 -class Sms(TwiML): - """ TwiML Noun """ + :returns: 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 element - def __init__(self, message, **kwargs): - super(Sms, self).__init__(**kwargs) - self.name = 'Sms' - self.value = message + :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: 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 element -class Say(TwiML): - """ TwiML Verb """ + :param action: Action URL + :param method: Action URL method + :param kwargs: additional attributes - def __init__(self, message, **kwargs): - super(Say, self).__init__(**kwargs) - self.name = 'Say' - self.value = message + :returns: element + """ + return self.nest(Start(action=action, method=method, **kwargs)) + def stop(self, **kwargs): + """ + Create a element + + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Stop(**kwargs)) + + def refer(self, action=None, method=None, **kwargs): + """ + Create a element + + :param action: Action URL + :param method: Action URL method + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Refer(action=action, method=method, **kwargs)) -class Reject(TwiML): - """ TwiML Verb """ + +class Refer(TwiML): + """ TwiML Verb""" def __init__(self, **kwargs): - super(Reject, self).__init__(**kwargs) - self.name = 'Reject' + super(Refer, self).__init__(**kwargs) + self.name = "Refer" + def sip(self, sip_url, **kwargs): + """ + Create a element -class Redirect(TwiML): - """ TwiML Verb """ + :param sip_url: SIP URL + :param kwargs: additional attributes - def __init__(self, url, **kwargs): - super(Redirect, self).__init__(**kwargs) - self.name = 'Redirect' - self.value = url + :returns: element + """ + return self.nest(ReferSip(sip_url, **kwargs)) -class Record(TwiML): - """ TwiML Verb """ +class ReferSip(TwiML): + """ TwiML Noun used in """ + + def __init__(self, sip_url, **kwargs): + super(ReferSip, self).__init__(**kwargs) + self.name = "Sip" + self.value = sip_url + + +class Stop(TwiML): + """ TwiML Verb""" def __init__(self, **kwargs): - super(Record, self).__init__(**kwargs) - self.name = 'Record' + 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 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 -class Queue(TwiML): - """ TwiML Noun """ + :returns: 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 element - def __init__(self, name, **kwargs): - super(Queue, self).__init__(**kwargs) - self.name = 'Queue' - self.value = name + :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: 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 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: 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): + """ TwiML Noun""" -class Play(TwiML): - """ TwiML Verb """ + def __init__(self, **kwargs): + super(Transcription, self).__init__(**kwargs) + self.name = "Transcription" - def __init__(self, url=None, **kwargs): - super(Play, self).__init__(**kwargs) - self.name = 'Play' - if url: - self.value = url + def config(self, name=None, value=None, **kwargs): + """ + Create a element + :param name: The name of the custom config + :param value: The value of the custom config + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Config(name=name, value=value, **kwargs)) + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) -class Pause(TwiML): - """ TwiML Verb """ + +class Parameter(TwiML): + """ TwiML Noun""" def __init__(self, **kwargs): - super(Pause, self).__init__(**kwargs) - self.name = 'Pause' + super(Parameter, self).__init__(**kwargs) + self.name = "Parameter" -class Leave(TwiML): - """ TwiML Verb """ +class Config(TwiML): + """ TwiML Noun""" def __init__(self, **kwargs): - super(Leave, self).__init__(**kwargs) - self.name = 'Leave' + super(Config, self).__init__(**kwargs) + self.name = "Config" -class Hangup(TwiML): - """ TwiML Verb """ +class Siprec(TwiML): + """ TwiML Noun""" def __init__(self, **kwargs): - super(Hangup, self).__init__(**kwargs) - self.name = 'Hangup' + super(Siprec, self).__init__(**kwargs) + self.name = "Siprec" + def parameter(self, name=None, value=None, **kwargs): + """ + Create a element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) -class Gather(TwiML): - """ TwiML Verb """ + +class Stream(TwiML): + """ TwiML Noun""" def __init__(self, **kwargs): - super(Gather, self).__init__(**kwargs) - self.name = 'Gather' + super(Stream, self).__init__(**kwargs) + self.name = "Stream" - def say(self, message, voice=None, loop=None, language=None, **kwargs): + def parameter(self, name=None, value=None, **kwargs): """ - Create a element + Create a element - :param message: Message to say - :param voice: Voice to use - :param loop: Times to loop message - :param language: Message langauge + :param name: The name of the custom parameter + :param value: The value of the custom parameter :param kwargs: additional attributes - :returns: element + :returns: element """ - return self.nest(Say(message, voice=voice, loop=loop, language=language, **kwargs)) + return self.nest(Parameter(name=name, value=value, **kwargs)) - def pause(self, length=None, **kwargs): + +class Start(TwiML): + """ 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 element + Create a element - :param length: Length in seconds to pause + :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: element + :returns: element """ - return self.nest(Pause(length=length, **kwargs)) + 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 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: 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 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: 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): + """ 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 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: element + """ + return self.nest( + Say(message=message, voice=voice, loop=loop, language=language, **kwargs) + ) def play(self, url=None, loop=None, digits=None, **kwargs): """ @@ -443,272 +984,2082 @@ def play(self, url=None, loop=None, digits=None, **kwargs): """ return self.nest(Play(url=url, loop=loop, digits=digits, **kwargs)) - -class Enqueue(TwiML): - """ 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): + def pause(self, length=None, **kwargs): """ - Create a element + Create a element - :param body: TaskRouter task attributes - :param priority: Task priority - :param timeout: Timeout associated with task + :param length: Length in seconds to pause :param kwargs: additional attributes - :returns: element + :returns: element """ - return self.nest(Task(body, priority=priority, timeout=timeout, **kwargs)) + return self.nest(Pause(length=length, **kwargs)) -class Task(TwiML): - """ TwiML Noun """ +class Pause(TwiML): + """ TwiML Verb""" - def __init__(self, body, **kwargs): - super(Task, self).__init__(**kwargs) - self.name = 'Task' - self.value = body + def __init__(self, **kwargs): + super(Pause, self).__init__(**kwargs) + self.name = "Pause" -class Echo(TwiML): - """ TwiML Verb """ +class Play(TwiML): + """ TwiML Verb""" - def __init__(self, **kwargs): - super(Echo, self).__init__(**kwargs) - self.name = 'Echo' + def __init__(self, url=None, **kwargs): + super(Play, self).__init__(**kwargs) + self.name = "Play" + if url: + self.value = url -class Dial(TwiML): - """ TwiML Verb """ +class Say(TwiML): + """ TwiML Verb""" - def __init__(self, number=None, **kwargs): - super(Dial, self).__init__(**kwargs) - self.name = 'Dial' - if number: - self.value = number + def __init__(self, message=None, **kwargs): + super(Say, self).__init__(**kwargs) + self.name = "Say" + if message: + self.value = message - def client(self, name, url=None, method=None, status_callback_event=None, - status_callback=None, status_callback_method=None, **kwargs): + def break_(self, strength=None, time=None, **kwargs): """ - Create a element + Create a element - :param name: Client name - :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 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: element + :returns: element """ - return self.nest(Client( - name, - 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, whisper=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, - **kwargs): + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + + def emphasis(self, words=None, level=None, **kwargs): """ - Create a element + Create a 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 whisper: Call whisper - :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 words: Words to emphasize + :param level: Specify the degree of emphasis :param kwargs: additional attributes - :returns: element + :returns: 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, - whisper=whisper, - 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, - **kwargs - )) - - def number(self, phone_number, send_digits=None, url=None, method=None, - status_callback_event=None, status_callback=None, - status_callback_method=None, **kwargs): + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + + def lang(self, words=None, xml_lang=None, **kwargs): """ - Create a element + Create a 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 words: Words to speak + :param xml:lang: Specify the language :param kwargs: additional attributes - :returns: element + :returns: 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, - **kwargs - )) + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) - def queue(self, name, url=None, method=None, reservation_sid=None, - post_work_activity_sid=None, **kwargs): + def p(self, words=None, **kwargs): """ - Create a element + Create a

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 words: Words to speak :param kwargs: additional attributes - :returns: element + :returns:

element """ - return self.nest(Queue( - name, - url=url, - method=method, - reservation_sid=reservation_sid, - post_work_activity_sid=post_work_activity_sid, - **kwargs - )) + return self.nest(SsmlP(words=words, **kwargs)) - def sim(self, sim_sid, **kwargs): + def phoneme(self, words, alphabet=None, ph=None, **kwargs): """ - Create a element + Create a element - :param sim_sid: SIM SID + :param words: Words to speak + :param alphabet: Specify the phonetic alphabet + :param ph: Specifiy the phonetic symbols for pronunciation :param kwargs: additional attributes - :returns: element + :returns: element """ - return self.nest(Sim(sim_sid, **kwargs)) + return self.nest(SsmlPhoneme(words, alphabet=alphabet, ph=ph, **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, **kwargs): + def prosody(self, words=None, volume=None, rate=None, pitch=None, **kwargs): """ - Create a element + Create a 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 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: element + :returns: 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, - **kwargs - )) + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) + def s(self, words=None, **kwargs): + """ + Create a element -class Sip(TwiML): - """ TwiML Noun """ + :param words: Words to speak + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlS(words=words, **kwargs)) + + def say_as(self, words, interpret_as=None, format=None, **kwargs): + """ + Create a 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: element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a 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: element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + def w(self, words=None, role=None, **kwargs): + """ + Create a 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: element + """ + return self.nest(SsmlW(words=words, role=role, **kwargs)) + + +class SsmlW(TwiML): + """Improving Pronunciation by Specifying Parts of Speech in """ + + 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 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: element + """ + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + + def emphasis(self, words=None, level=None, **kwargs): + """ + Create a element + + :param words: Words to emphasize + :param level: Specify the degree of emphasis + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + + def phoneme(self, words, alphabet=None, ph=None, **kwargs): + """ + Create a 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: 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 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: 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 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: element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a 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: element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + +class SsmlSub(TwiML): + """Pronouncing Acronyms and Abbreviations in """ + + 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 """ + + 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 """ + + 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 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: element + """ + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + + def emphasis(self, words=None, level=None, **kwargs): + """ + Create a element + + :param words: Words to emphasize + :param level: Specify the degree of emphasis + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + + def lang(self, words=None, xml_lang=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param xml:lang: Specify the language + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) + + def p(self, words=None, **kwargs): + """ + Create a

element + + :param words: Words to speak + :param kwargs: additional attributes + + :returns:

element + """ + return self.nest(SsmlP(words=words, **kwargs)) + + def phoneme(self, words, alphabet=None, ph=None, **kwargs): + """ + Create a 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: 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 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: element + """ + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) + + def s(self, words=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlS(words=words, **kwargs)) + + def say_as(self, words, interpret_as=None, format=None, **kwargs): + """ + Create a 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: element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a 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: element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + def w(self, words=None, role=None, **kwargs): + """ + Create a 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: element + """ + return self.nest(SsmlW(words=words, role=role, **kwargs)) + + +class SsmlS(TwiML): + """Adding A Pause Between Sentences in """ + + 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 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: element + """ + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + + def emphasis(self, words=None, level=None, **kwargs): + """ + Create a element + + :param words: Words to emphasize + :param level: Specify the degree of emphasis + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + + def lang(self, words=None, xml_lang=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param xml:lang: Specify the language + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) + + def phoneme(self, words, alphabet=None, ph=None, **kwargs): + """ + Create a 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: 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 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: 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 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: element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a 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: element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + def w(self, words=None, role=None, **kwargs): + """ + Create a 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: element + """ + return self.nest(SsmlW(words=words, role=role, **kwargs)) + + +class SsmlPhoneme(TwiML): + """Using Phonetic Pronunciation in """ + + 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 """ + + 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 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: element + """ + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + + def emphasis(self, words=None, level=None, **kwargs): + """ + Create a element + + :param words: Words to emphasize + :param level: Specify the degree of emphasis + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + + def lang(self, words=None, xml_lang=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param xml:lang: Specify the language + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) + + def p(self, words=None, **kwargs): + """ + Create a

element + + :param words: Words to speak + :param kwargs: additional attributes + + :returns:

element + """ + return self.nest(SsmlP(words=words, **kwargs)) + + def phoneme(self, words, alphabet=None, ph=None, **kwargs): + """ + Create a 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: 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 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: element + """ + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) + + def s(self, words=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlS(words=words, **kwargs)) + + def say_as(self, words, interpret_as=None, format=None, **kwargs): + """ + Create a 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: element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a 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: element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + def w(self, words=None, role=None, **kwargs): + """ + Create a 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: element + """ + return self.nest(SsmlW(words=words, role=role, **kwargs)) + + +class SsmlP(TwiML): + """Adding a Pause Between Paragraphs in """ + + 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 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: element + """ + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + + def emphasis(self, words=None, level=None, **kwargs): + """ + Create a element + + :param words: Words to emphasize + :param level: Specify the degree of emphasis + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + + def lang(self, words=None, xml_lang=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param xml:lang: Specify the language + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) + + def phoneme(self, words, alphabet=None, ph=None, **kwargs): + """ + Create a 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: 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 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: element + """ + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) + + def s(self, words=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlS(words=words, **kwargs)) + + def say_as(self, words, interpret_as=None, format=None, **kwargs): + """ + Create a 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: element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a 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: element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + def w(self, words=None, role=None, **kwargs): + """ + Create a 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: element + """ + return self.nest(SsmlW(words=words, role=role, **kwargs)) + + +class SsmlEmphasis(TwiML): + """Emphasizing Words in """ + + 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 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: element + """ + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + + def emphasis(self, words=None, level=None, **kwargs): + """ + Create a element + + :param words: Words to emphasize + :param level: Specify the degree of emphasis + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + + def lang(self, words=None, xml_lang=None, **kwargs): + """ + Create a element + + :param words: Words to speak + :param xml:lang: Specify the language + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) + + def phoneme(self, words, alphabet=None, ph=None, **kwargs): + """ + Create a 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: 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 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: 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 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: element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a 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: element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + def w(self, words=None, role=None, **kwargs): + """ + Create a 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: element + """ + return self.nest(SsmlW(words=words, role=role, **kwargs)) + + +class SsmlBreak(TwiML): + """Adding a Pause in """ + + def __init__(self, **kwargs): + super(SsmlBreak, self).__init__(**kwargs) + self.name = "break" + + +class Pay(TwiML): + """ 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 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: 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 element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Sms(TwiML): + """ TwiML Noun""" + + def __init__(self, message, **kwargs): + super(Sms, self).__init__(**kwargs) + self.name = "Sms" + self.value = message + + +class Reject(TwiML): + """ TwiML Verb""" + + def __init__(self, **kwargs): + super(Reject, self).__init__(**kwargs) + self.name = "Reject" + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Redirect(TwiML): + """ TwiML Verb""" + + def __init__(self, url, **kwargs): + super(Redirect, self).__init__(**kwargs) + self.name = "Redirect" + self.value = url + + +class Record(TwiML): + """ TwiML Verb""" + + def __init__(self, **kwargs): + super(Record, self).__init__(**kwargs) + self.name = "Record" + + +class Queue(TwiML): + """ TwiML Noun""" + + def __init__(self, name, **kwargs): + super(Queue, self).__init__(**kwargs) + self.name = "Queue" + self.value = name + + +class Leave(TwiML): + """ TwiML Verb""" + + def __init__(self, **kwargs): + super(Leave, self).__init__(**kwargs) + self.name = "Leave" + + +class Hangup(TwiML): + """ TwiML Verb""" + + def __init__(self, **kwargs): + super(Hangup, self).__init__(**kwargs) + self.name = "Hangup" + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Gather(TwiML): + """ 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 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: element + """ + return self.nest( + Say(message=message, voice=voice, loop=loop, language=language, **kwargs) + ) + + def pause(self, length=None, **kwargs): + """ + Create a element + + :param length: Length in seconds to pause + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Pause(length=length, **kwargs)) + + def play(self, url=None, loop=None, digits=None, **kwargs): + """ + Create a element + + :param url: Media URL + :param loop: Times to loop media + :param digits: Play DTMF tones for digits + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Play(url=url, loop=loop, digits=digits, **kwargs)) + + +class Enqueue(TwiML): + """ 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 element + + :param body: TaskRouter task attributes + :param priority: Task priority + :param timeout: Timeout associated with task + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Task(body, priority=priority, timeout=timeout, **kwargs)) + + +class Task(TwiML): + """ TwiML Noun""" + + def __init__(self, body, **kwargs): + super(Task, self).__init__(**kwargs) + self.name = "Task" + self.value = body + + +class Echo(TwiML): + """ TwiML Verb""" + + def __init__(self, **kwargs): + super(Echo, self).__init__(**kwargs) + self.name = "Echo" + + +class Dial(TwiML): + """ 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 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: 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 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: 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 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: 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 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: 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 element + + :param sim_sid: SIM SID + :param kwargs: additional attributes + + :returns: 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 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: 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 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: 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): + """ 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 element + + :param sid: Application sid to dial + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(ApplicationSid(sid, **kwargs)) + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class ApplicationSid(TwiML): + """ TwiML Noun""" + + def __init__(self, sid, **kwargs): + super(ApplicationSid, self).__init__(**kwargs) + self.name = "ApplicationSid" + self.value = sid + + +class Sip(TwiML): + """ TwiML Noun""" def __init__(self, sip_url, **kwargs): super(Sip, self).__init__(**kwargs) - self.name = 'Sip' + self.name = "Sip" self.value = sip_url class Sim(TwiML): - """ TwiML Noun """ + """ TwiML Noun""" def __init__(self, sim_sid, **kwargs): super(Sim, self).__init__(**kwargs) - self.name = 'Sim' + self.name = "Sim" self.value = sim_sid class Number(TwiML): - """ TwiML Noun """ + """ TwiML Noun""" def __init__(self, phone_number, **kwargs): super(Number, self).__init__(**kwargs) - self.name = 'Number' + self.name = "Number" self.value = phone_number class Conference(TwiML): - """ TwiML Noun """ + """ TwiML Noun""" def __init__(self, name, **kwargs): super(Conference, self).__init__(**kwargs) - self.name = 'Conference' + self.name = "Conference" self.value = name class Client(TwiML): - """ TwiML Noun """ + """ TwiML Noun""" - def __init__(self, name, **kwargs): + def __init__(self, identity=None, **kwargs): super(Client, self).__init__(**kwargs) - self.name = 'Client' + self.name = "Client" + if identity: + self.value = identity + + def identity(self, client_identity, **kwargs): + """ + Create a element + + :param client_identity: Identity of the client to dial + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Identity(client_identity, **kwargs)) + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Identity(TwiML): + """ TwiML Noun""" + + def __init__(self, client_identity, **kwargs): + super(Identity, self).__init__(**kwargs) + self.name = "Identity" + self.value = client_identity + + +class Connect(TwiML): + """ TwiML Verb""" + + def __init__(self, **kwargs): + super(Connect, self).__init__(**kwargs) + self.name = "Connect" + + def room(self, name, participant_identity=None, **kwargs): + """ + Create a element + + :param name: Room name + :param participant_identity: Participant identity when connecting to the Room + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Room(name, participant_identity=participant_identity, **kwargs) + ) + + def autopilot(self, name, **kwargs): + """ + Create a element + + :param name: Autopilot assistant sid or unique name + :param kwargs: additional attributes + + :returns: 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 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: 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 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: 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 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: 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 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: 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 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: 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): + """ 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 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: 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 element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Language(TwiML): + """ TwiML Noun""" + + def __init__(self, **kwargs): + super(Language, self).__init__(**kwargs) + self.name = "Language" + + +class ConversationRelay(TwiML): + """ 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 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: 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 element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Conversation(TwiML): + """ TwiML Noun""" + + def __init__(self, **kwargs): + super(Conversation, self).__init__(**kwargs) + self.name = "Conversation" + + +class VirtualAgent(TwiML): + """ TwiML Noun""" + + def __init__(self, **kwargs): + super(VirtualAgent, self).__init__(**kwargs) + self.name = "VirtualAgent" + + def config(self, name=None, value=None, **kwargs): + """ + Create a element + + :param name: The name of the custom config + :param value: The value of the custom config + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Config(name=name, value=value, **kwargs)) + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Autopilot(TwiML): + """ TwiML Noun""" + + def __init__(self, name, **kwargs): + super(Autopilot, self).__init__(**kwargs) + self.name = "Autopilot" + self.value = name + + +class Room(TwiML): + """ TwiML Noun""" + + def __init__(self, name, **kwargs): + super(Room, self).__init__(**kwargs) + self.name = "Room" self.value = name